Documente Academic
Documente Profesional
Documente Cultură
Student Handout.
Software required.
Eclipse Europa.
HSQL Database.
Exercise 1 a
Step 1.
Jar files required for the simple Hibernate application.Add to the build path.
cglib-nodep-2.1_3.jar
commons-collection.jar
commons-logging.jar
dom4j-1.6.1.jar
hibernate3.jar
hsqldb.jar
jta.jar
Step 2.
The sample programs are executed in HSQL Server .Create a sample database called
mydb.xdb is the alias name.
java cp ../lib/hsqldb.jar org.hsqldb.Server database.0 mydb dbname.0
xdb
Make sure u have hsqldb.jar. Type the above in the command line. This creates a database
named xdb.
The above command runs a tool,so that u can view you files.
Database Tool.
Select HSQL Database Engine Server.
Write the following URL.
jdbc:hsqldb:hsql://localhost:9001/xdb
Leave the other columns as is.
Step 3.
Create a Java Project using Eclipse.
To the source folder, add the following 3 java files.
HibernateUtil.java
import org.hibernate.*;
import org.hibernate.cfg.*;
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);
}
}
EventManager.java
import org.hibernate.Transaction;
import org.hibernate.Session;
Transaction tx = session.beginTransaction();
Person theperson = new Person();
theperson.setAge(10);
theperson.setFirstname("Susithra");
theperson.setLastname("Chandrabose");
session.save(theperson);
tx.commit();
System.out.println("Person is stored");
HibernateUtil.closeSession();
HibernateUtil.sessionFactory.close();
}
}
Person.java
import java.util.*;
Person() {}
hibernate.cfg.xml
<?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-configuration>
<session-factory>
<property
name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property
name="connection.url">jdbc:hsqldb:hsql://localhost:9001/xdb</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<property
name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Person" table="PERSON">
<id name="id" column="PERSON_ID">
<generator class="increment"/>
</id>
<property name="age"/>
<property name="firstname"/>
<property name="lastname"/>
</class>
</hibernate-mapping>
Now we have successfully created a table. We will add few more rows to it. Comment on
the following line
Add different persons. Run the application and check the database.
• Transient - an object is transient if it has just been instantiated using the new operator,
and it is not associated with a Hibernate Session. It has no persistent representation in
the database and no identifier value has been assigned. Transient instances will be
destroyed by the garbage collector if the application doesn't hold a reference anymore.
Use the Hibernate Session to make an object persistent (and let Hibernate take care of
the SQL statements that need to be executed for this transition).
• Persistent - a persistent instance has a representation in the database and an identifier
value. It might just have been saved or loaded, however, it is by definition in the scope of
a Session. Hibernate will detect any changes made to an object in persistent state and
synchronize the state with the database when the unit of work completes. Developers
don't execute manual UPDATE statements, or DELETE statements when an object should
be made transient.
• Detached - a detached instance is an object that has been persistent, but its Session has
been closed. The reference to the object is still valid, of course, and the detached instance
might even be modified in this state. A detached instance can be reattached to a new
Session at a later point in time, making it (and all the modifications) persistent again.
This feature enables a programming model for long running units of work that require
user think-time. We call them application transactions, i.e. a unit of work from the point
of view of the user.
To Load an Object
import org.hibernate.Transaction;
import org.hibernate.Session;
public class EventManager {
Transaction tx = session.beginTransaction();
Person theperson = new Person();
theperson.setAge(30);
theperson.setFirstname("Subbu");
theperson.setLastname("David");
session.save(theperson);
tx.commit();
//Loading an Object
HibernateUtil.closeSession();
HibernateUtil.sessionFactory.close();
}
Exercise 1 b
Querying(HQL)
Add the following lines inside the active session to list all the persons using createQuery
List persons = session.createQuery("from Person as
person").list();
Iterator i= persons.iterator();
while(i.hasNext()){
System.out.println(" "+i.next());
}
Queries may specify a property of a class in the select clause. They may even call SQL
aggregate functions. Properties or aggregates are considered "scalar" results (and not
entities in persistent state).
Exercise 2 a
Relationships.
One to One associations two varieties .Primary key association as well as unique foreign
key associations .The following example shows
One to One association (Unique foreign key associations)
One person can have an address .The Address is a member of Person class.
Address.java
package com.accenture.domain;
Person.java
package com.accenture.domain;
Person.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.accenture.domain">
<!-- One to One Unidirectional -->
<class name="Person">
<id name="id"
column="personId">
<generator class="increment"/>
</id>
<property name="name" column="PERSONNAME"
type="java.lang.String" />
<many-to-one name="address"
column="addressId"
not-null="true" lazy="false" unique="true"/>
</class>
<class name="Address">
<id name="id"
column="addressId">
<generator class="increment"/>
</id>
<property name="city" column="CITY" type="java.lang.String"
/>
<property name="country" column="COUNTRY"
type="java.lang.String" />
</class>
</hibernate-mapping>
The mapping file remains the same. But except give the complete path
<mapping resource="com/accenture/domain/Person.hbm.xml"/>
package com.accenture.client;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.accenture.Utilities.HibernateUtil;
import com.accenture.domain.Address;
import com.accenture.domain.Person;
public class EventManager {
Transaction tx = session.beginTransaction();
Address address=new Address();
address.setCity("Bangalore");
address.setCountry("India");
session.save(address);
Person theperson = new Person();
theperson.setName("Susithra C");
theperson.setAddress(address);
session.save(theperson);
tx.commit();
HibernateUtil.closeSession();
HibernateUtil.sessionFactory.close();
}}
Exercise 2 b
One to Many association (Bi Directional)
Child.java
package com.accenture.domain;
package com.accenture.domain;
import java.util.HashSet;
import java.util.Set;
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="com.accenture.domain">
<class name="Parent">
<id name="id"
column="parent_id">
<generator class="increment"/>
</id>
<property name="name"/>
<set name="children"
table="ParentChild"
cascade="all"
inverse="true" lazy="false">
<key column="parent_id"/>
<many-to-many column="child_id"
class="Child"/>
</set>
</class>
<class name="Child">
<id name="id"
column="child_id">
<generator class="increment"/>
</id>
<property name="name"/>
<join table="ParentChild"
optional="true">
<key column="child_id"/>
<many-to-one name="parent"
column="parent_id"
not-null="true"/>
</join>
</class>
</hibernate-mapping>
EventManager.java
package com.accenture.client;
import java.util.HashSet;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hsqldb.lib.Set;
import com.accenture.Utilities.HibernateUtil;
import com.accenture.domain.*;
Transaction tx = session.beginTransaction();
Parent parent=new Parent();
parent.setName("Father");
HibernateUtil.closeSession();
HibernateUtil.sessionFactory.close();
}
}
Enforced in the underlying database by a join table. Check the tables.
Exercise 2c
Person.java
package com.accenture.domain;
Employee.java
package com.accenture.domain;
}
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.accenture.domain">
<class name="Person" table="PERSON">
<id name="id" column="PERSON_ID">
<generator class="foreign">
<param name="property">employee</param>
</generator>
</id>
<property name="name" column="name" type="java.lang.String" />
<one-to-one name="employee"
class="Employee"
constrained="true"/>
</class>
<class name="Employee">
<id name="id"
column="empId">
<generator class="increment"/>
</id>
EventManager.java
package com.accenture.client;
import java.util.HashSet;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hsqldb.lib.Set;
import com.accenture.Utilities.HibernateUtil;
import com.accenture.domain.Employee;
import com.accenture.domain.Person;
Exercise 3a
Inheritance Relationships. Other files remains the same.
Tab1.java
package com.accenture.domain;
public class Tab1 extends TblPerClass {
protected String desctwo = null;
public String getDesctwo() {
return desctwo;
}
public void setDesctwo(String desctwo) {
this.desctwo = desctwo;
}
}
Tab2.java
package com.accenture.domain;
TblPerClass.java
package com.accenture.domain;
import java.util.Date;
TblPerClass.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.accenture.domain">
<class name="TblPerClass" table="TBLPERCLASS"
polymorphism="implicit">
<id name="id" column="ID">
<generator class="increment"/>
</id>
<discriminator>
<column name="DISCRIMINATOR"/>
</discriminator>
<property name="date" column="DATE" type="java.sql.Date" />
<subclass name="Tab1" discriminator-value="tab1">
<property name="desctwo" column="DESCTWO"
type="java.lang.String" />
</subclass>
<subclass name="Tab2" discriminator-value="tab2">
<property name="desc" column="DESC"
type="java.lang.String" />
</subclass>
</class>
</hibernate-mapping>
EventManager.java
package com.accenture.client;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.accenture.Utilities.HibernateUtil;
import com.accenture.domain.Tab1;
import com.accenture.domain.Tab2;
Transaction tx = session.beginTransaction();
tx.commit();
HibernateUtil.closeSession();
HibernateUtil.sessionFactory.close();
}
}
Here check the tables. Only TabPerClass is created. No tables are created for the
subclasses. Only tables are generated for the super class.
Exercise 3b
The following example shows all the sub class super Class is not created.
Tab5.java
package samples;
/**
* @return Returns the address.
*/
public String getXyz1() {
return xyz1;
}
/**
* @param address The address to set.
*/
public void setXyz1(String xyz1) {
this.xyz1 = xyz1;
}
}
Tab6.java
package samples;
/**
* @return Returns the address.
*/
public String getXyz2() {
return xyz2;
}
/**
* @param address The address to set.
*/
public void setXyz2(String xyz2) {
this.xyz2 = xyz2;
}
}
TblPerConcreteClass.java
package samples;
import java.util.Set;
}
EntityManager.java
package samples;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.accenture.Utilities.HibernateUtil;
import com.accenture.domain.Tab1;
import com.accenture.domain.Tab2;
Transaction tx = session.beginTransaction();
tx.commit();
HibernateUtil.closeSession();
HibernateUtil.sessionFactory.close();
}
TblPerConcreteClass.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="samples.Tab5" table="TAB5" polymorphism="implicit">
<id name="id" column="ID">
<generator class="increment"/>
</id>
<property name="description" column="DESCRIPTION"
type="java.lang.String" />
<property name="xyz1" column="XYZ1"
type="java.lang.String"/>
</class>
package samples;
}
Tab4.java
package samples;
}
TblPerSubClass.java
package samples;
import java.util.Set;
}
TblPerSubClass.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="samples.TblPerSubClass" table="TBLPERSUBCLASS"
polymorphism="implicit">
<id name="id" column="ID">
<generator class="increment"/>
</id>
<joined-subclass name="samples.Tab3" table="TAB3">
<key column="id"/>
<property name="firstName" column="FIRST_NAME"
type="java.lang.String" />
<property name="lastName" column="LAST_NAME"
type="java.lang.String" />
</joined-subclass>
<joined-subclass name="samples.Tab4" table="TAB4">
<key column="id"/>
<property name="name" column="NAME" type="string" />
<property name="registrationNumber"
column="REGISTRATION_NUMBER" type="string" />
</joined-subclass>
</class>
</hibernate-mapping>
EventManager.java
package samples;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.accenture.Utilities.HibernateUtil;
import com.accenture.domain.Tab1;
import com.accenture.domain.Tab2;
Transaction tx = session.beginTransaction();
tx.commit();
HibernateUtil.closeSession();
HibernateUtil.sessionFactory.close();
}
}
Exercise for the students .Observe the difference.Check the database.
Hibernate Annotations.
Employee.java
package com.accenture;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
public Employee() {
}
@Id
@Column(name = "id")
Integer id;
@Column(name = "name")
String name;
Example1.java
package com.accenture;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/**
* @param args
*/
public static void main(String[] args) throws Exception {
/** Getting the Session Factory and session */
SessionFactory session = HibernateUtil.getSessionFactory();
Session sess = session.getCurrentSession();
/** Starting the Transaction */
Transaction tx = sess.beginTransaction();
/** Creating Pojo */
Employee pojo = new Employee();
pojo.setId(new Integer(5));
pojo.setName("XYZ");
/** Saving POJO */
sess.save(pojo);
/** Commiting the changes */
tx.commit();
System.out.println("Record Inserted");
/** Closing Session */
session.close();
}
HibernateUtils.java
package com.accenture;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
hibernate.cfg.xml
<hibernate-configuration>
<session-factory >
<property
name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property
name="connection.url">jdbc:hsqldb:hsql://localhost:9001/xdb</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<property name="connection.pool_size">10</property>
<property
name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Disable the second-level cache -->
<property
name="cache.provider_class">org.hibernate.cache.NoCacheProvider</proper
ty>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.accenture.Employee"/>
</session-factory>
</hibernate-configuration>