Hibernate: Understanding Associations - Associations in the Real World
(Page 4 of 4 )
Till now I was using only one table. Let's make things interesting by adding one more table. This table is the Product table. Each Order can have more than one Product. Hence the relationship between Order and Product is One-to-Many. The schema of the Product table is:
CREATE TABLE PRODUCT(
ID VARCHAR NOT NULL PRIMARY KEY,
NAME VARCHAR NOT NULL,
PRICE DOUBLE NOT NULL,
AMOUNT INTEGER NOT NULL,
ORDER_ID VARCHAR NOT NULL)
The next step is to create the persistent class for the Product table. The persistent class is as follows:
package com.someorg.persist;
public class Product {
private String id;
private String name;
private double price;
private int amount;
private Order order;
public Product(String id, String name, double price, int amount, Order
order)
{
this.order=order;
//others not shown for brevity
}
public String getId() {
return id;
}
public void setId(String string) {
id = string;
}
// default constructor and other
// getters/setters not shown for brevity
// ...
}
The next part is Product.hbm.xml, that is the mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="test.hibernate.Product"
table="products">
<id name="id" type="string"
unsaved-value="null">
<column name="id" sql-type="char(32)"
not-null="true"/>
<generator class="assigned"/>
</id>
<property name="name">
<column name="name" sql-type="char(255)"
not-null="true"/>
</property>
<property name="price">
<column name="price" sql-type="double"
not-null="true"/>
</property>
<property name="amount">
<column name="amount" sql-type="integer"
not-null="true"/>
</property>
<property name="orderId">
<column name="ORDER_ID" sql-type="char(255)"
not-null="true"/>
<many-to-one
name="orderId"
column="ORDER_ID"
class="ORDER"
not-null="true"/>
</class>
</hibernate-mapping>
That is all that is required for the Product table. Now we need to make some changes in the Order class.
package com.someorg.persist;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Order {
private String id;
private Date date;
private double priceTotal;
private Set products =new HashSet();
// Automatically set the creation time of
// this Order
public Order() {
this.date = new Date();
}
public Order(String id, Date date, private double priceTotal, Set products){
this.products=products;
//others are not shown for brevity
}
public String getId() {
return id;
}
public void setProducts(Set products) {
this.products = products;
}
public Set getProducts () {
return products;
}
public void setId(String string) {
id = string;
}
// other getters/setters not shown for
// brevity
// ...
}
The next part is changing in the Order.hbm.xml, which is:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-mapping default-cascade="none" default-access="property" auto-import="true">
<class name=" com.someorg.persist.Order" table="orders" mutable="true" select- before-update="false" optimistic-lock="version">
<id name="id" type="string" unsaved-value="null">
<column name="id" sql-type="char(32)" not-null="true" />
<generator class="assigned" />
</id>
<property name="date" not-null="false" >
<column name="order_date" sql-type="datetime" not-null="true" />
</property>
<property name="priceTotal" not-null="false" >
<column name="price_total" sql-type="double" not-null="true" />
</property>
<set name="products">
<key column="PRODUCT_ID"/>
<one-to-many class="Product"/>
</set>
</class>
</hibernate-mapping>
The next step is to test it. To test it I will be using the Criteria query. In a QBC the joins are done using the setFetchMode method of the Criteria class. The mode would be JOIN. Here is how it works:
import java.util.List;
//other imports
// use as
// java test. FindOrderById name
public class FindOrderById {
public static void main(String[] args) throws Exception {
// query to issue
String query =
"select order from Order "
+ "where order.id=:id";
// search for what?
String name = args[0];
// init
Configuration cfg = new Configuration()
.addClass(Order.class);
SessionFactory sf = cfg.buildSessionFactory();
// open session
Session sess = sf.openSession();
// search and return
Criteria criteria = session.createCriteria(Order.class);
criteria.add( Expression.eq("id", name) )
.setFetchMode(“products”,FetchMode.JOIN);
List result = criteria.list();
if (list.size() == 0) {
System.out.println("No Order having id "
+ name);
System.exit(0);
}
Order o = (Order) list.get(0);
sess.close();
System.out.println("Found Order: " + o);//this is just an example Here the o //
//object can be traversed to achieve anything
}
}
That brings us to the end of this discussion. Though the complete picture is becoming clear, some edges are still hazy. These edges will be brought into sharper focus in the forthcoming discussions. Till next time.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |