Hibernate test driver

In the last tutorial a number of Java objects were created and the values persisted to the various database tables under the management of Hibernate. Now, we will create a very simple test program to load the data back from the database and display it to the console.

We can do this by choosing one Person object and iterating over all the associated objects that it contains.

The following code will show the effect of Hibernate re-constituting objects from the database.

[code lang=”Java”]
package alphastar.main;

import java.util.Iterator;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;

import alphastar.model.Person;
import alphastar.model.Stock;
import alphastar.model.StockEvent;

public class ReadStock {

public void process() {
Transaction txn = null;
Session session = HibernateUtil.getSessionFactory().openSession();
txn = session.beginTransaction();
try {
// get a Person by id
Object a = session.get(Person.class, new Integer(2));
Person p = (Person)a;
System.out.println(“Name: “+p.getName());

Iterator i = p.getStocksHeld().iterator();
while (i.hasNext()) {
Object o = i.next();
Stock stock = (Stock)o;
System.out.println(“Code: “+stock.getCode());
System.out.println(“Name: “+stock.getName());
// Iterate over all the stockheld instances

Set stockEvents = stock.getStockEvents();
Iterator i2 = stockEvents.iterator();
while (i2.hasNext()) {
Object o2 = i2.next();
StockEvent se = (StockEvent) o2;
System.out.println(“Buy Date: “+se.getBuyDate());
System.out.println(“Buy Price: “+se.getBuyPrice());
System.out.println(“Sold Date: “+se.getSoldDate());
System.out.println(“Sold Price: “+se.getSoldPrice());
System.out.println(“—————-“);
}
}

txn.commit();
//session.close();
} catch (RuntimeException e) {
if(session.getTransaction() != null){
session.getTransaction().rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
}

}

[/code]

As seen above, we select a Person id (in this example we choose 2, which is a PK (idperson) to the Person table. The intersting part is that a top level object with object references to other classes are automatically loaded in one go.
So from loading the Person object (only) we were given the associated Stock objects, and from the Stock objects, the StockEvent objects were loaded.

code

Place the file in the “main” directory of the project

The file is here

Leave a Reply

Your email address will not be published. Required fields are marked *