This article, the third in our series on Hibernate, focuses on the life-cycle states of persistent objects and associations. These concepts are put to work with continued development of an application that was created in the first two articles of this series.
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:
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 {
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.