Java/Hibernate/Hibernate Transaction
Hibernate Transaction With Try Catch
/////////////////////////////////////////////////////////////////////////
import java.io.Serializable;
import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.*;
import org.hibernate.event.*;
import org.hibernate.event.def.*;
public class Main {
public static void main(String[] args) throws Exception {
HibernateUtil.setup("create table grouptable (id int,name varchar);");
HibernateUtil.setup("create table story (id int,info varchar,idx int,parent_id int);");
Session session = HibernateUtil.currentSession();
Group sp = new Group("Group Name");
ArrayList list = new ArrayList();
list.add(new Story("Story Name 1"));
list.add(new Story("Story Name 2"));
sp.setStories(list);
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(sp);
transaction.rumit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
throw e;
}
} finally {
session.close();
}
HibernateUtil.checkData("select * from grouptable");
HibernateUtil.checkData("select * from story");
}
}
/////////////////////////////////////////////////////////////////////////
import java.util.*;
public class Story {
private int id;
private String info;
public Story(){
}
public Story(String info) {
this.info = info;
}
public void setId(int i) {
id = i;
}
public int getId() {
return id;
}
public void setInfo(String n) {
info = n;
}
public String getInfo() {
return info;
}
}
/////////////////////////////////////////////////////////////////////////
import java.util.*;
public class Group {
private int id;
private String name;
private List stories;
public Group(){
}
public Group(String name) {
this.name = name;
}
public void setId(int i) {
id = i;
}
public int getId() {
return id;
}
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
public void setStories(List l) {
stories = l;
}
public List getStories() {
return stories;
}
}
/////////////////////////////////////////////////////////////////////////
<?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="Group" table="grouptable">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<list name="stories" cascade="all">
<key column="parent_id"/>
<index column="idx"/>
<one-to-many class="Story"/>
</list>
<property name="name" type="string"/>
</class>
<class name="Story"
table="story">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="info"/>
</class>
</hibernate-mapping>
/////////////////////////////////////////////////////////////////////////
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this thread has none yet
if (s == null) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
static Connection conn;
static Statement st;
public static void setup(String sql) {
try {
// Step 1: Load the JDBC driver.
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
// Step 2: Establish the connection to the database.
String url = "jdbc:hsqldb:data/tutorial";
conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
st.executeUpdate(sql);
} catch (Exception e) {
System.err.println("Got an exception! ");
e.printStackTrace();
System.exit(0);
}
}
public static void checkData(String sql) {
try {
HibernateUtil.outputResultSet(st
.executeQuery(sql));
// conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void outputResultSet(ResultSet rs) throws Exception{
ResultSetMetaData metadata = rs.getMetaData();
int numcols = metadata.getColumnCount();
String[] labels = new String[numcols];
int[] colwidths = new int[numcols];
int[] colpos = new int[numcols];
int linewidth;
for (int i = 0; i < numcols; i++) {
labels[i] = metadata.getColumnLabel(i + 1); // get its label
System.out.print(labels[i]+" ");
}
System.out.println("------------------------");
while (rs.next()) {
for (int i = 0; i < numcols; i++) {
Object value = rs.getObject(i + 1);
if(value == null){
System.out.print(" ");
}else{
System.out.print(value.toString().trim()+" ");
}
}
System.out.println(" ");
}
}
}
/////////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:data/tutorial</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Mapping files -->
<mapping resource="Group.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Transaction Rollback Illustration
/////////////////////////////////////////////////////////////////////////
import java.util.*;
import java.sql.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.criterion.*;
public class Main {
public static void main(String[] args) {
HibernateUtil.setup("create table Supplier ( id int, name VARCHAR);");
HibernateUtil.setup("create table Product ( id int, name VARCHAR, description VARCHAR, price double,supplierId int);");
prepareData();
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Product p = null;
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
p = (Product)session.createQuery("from Product where name="Product 1"").uniqueResult();
tx.rumit();
System.out.println("Username of p acquired from DB... " + p.getName());
System.out.println("Begin transaction:");
tx = session.beginTransaction();
System.out.println("Change name of p");
p.setName("quentin");
System.out.println("Username of p before rollback... " + p.getName());
tx.rollback();
System.out.println("Username of p after rollback... " + p.getName());
tx = session.beginTransaction();
System.out.println("About to refresh p!");
session.refresh(p);
System.out.println("Username of p after refresh... " + p.getName());
tx.rumit();
System.out.println("Username of p after commit... " + p.getName());
HibernateUtil.checkData("select * from Supplier");
HibernateUtil.checkData("select * from Product");
}
static public void displaySupplierList(List list) {
Iterator iter = list.iterator();
if (!iter.hasNext()) {
System.out.println("No suppliers to display.");
return;
}
while (iter.hasNext()) {
Supplier supplier = (Supplier) iter.next();
String msg = supplier.getName();
System.out.println(msg);
}
}
private static void prepareData(){
Session session = HibernateUtil.currentSession();
Supplier supplier1 = new Supplier();
supplier1.setName("Supplier Name 1");
session.save(supplier1);
Supplier supplier2 = new Supplier();
supplier2.setName("Supplier Name 2");
session.save(supplier2);
Product product1 = new Product("Product 1","Name for Product 1", 2.0);
product1.setSupplier(supplier1);
supplier1.getProducts().add(product1);
session.save(product1);
Product product12 = new Product("Product 2","Name for Product 2", 22.0);
product12.setSupplier(supplier1);
supplier1.getProducts().add(product12);
session.save(product12);
Product product2 = new Product("Product 3", "Name for Product 3", 30.0);
product2.setSupplier(supplier2);
supplier2.getProducts().add(product2);
session.save(product2);
session.flush();
HibernateUtil.closeSession();
}
}
/////////////////////////////////////////////////////////////////////////
public class Product
{
private int id;
private Supplier supplier;
private String name;
private String description;
private double price;
public Product()
{
super();
}
public Product(String name, String description, double price)
{
super();
this.name = name;
this.description = description;
this.price = price;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Supplier getSupplier()
{
return supplier;
}
public void setSupplier(Supplier supplier)
{
this.supplier = supplier;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
}
/////////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Supplier">
<id name="id" type="int">
<generator class="increment"/>
</id>
<property name="name" type="string"/>
<bag name="products" inverse="true" cascade="all,delete-orphan">
<key column="supplierId"/>
<one-to-many class="Product"/>
</bag>
</class>
</hibernate-mapping>
/////////////////////////////////////////////////////////////////////////
import java.util.ArrayList;
import java.util.List;
public class Supplier
{
private int id;
private String name;
private List products = new ArrayList();
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public List getProducts()
{
return products;
}
public void setProducts(List products)
{
this.products = products;
}
}
/////////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:data/tutorial</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Mapping files -->
<mapping resource="Product.hbm.xml"/>
<mapping resource="Supplier.hbm.xml"/>
</session-factory>
</hibernate-configuration>