One-to-One Mapping in Hibernate Using Foreign Key Association
One-to-One Mapping in Hibernate Using Foreign Key Association
com/blog/2010/02/10/mapping-composite-keys-in-hibernate/
My previous post described about the Primary key one-to-one mapping in Hibernate.
This post gives an example of Foreign key one-to-one association in Hibernate.
In Foreign key one-to-one mapping, 2 entities will have one to one association using
foreign keys. one table holds primary key of 2nd table. Eg: consider Customer and
address entities. In primary key association, both the tables share same primary key.
In foreign key association, customer table will have a address_id columns, in which
primary key (address_id) of the customer’s address will be saved. Both customer and
address tables will have different primary keys.
Address is a simple table and customer table contains a column to store the
corresponding address_id.
Corresponding Beans would be with following fields and their getter and setter
methods:
long addressId;
String addressLine1;
String addressLine2;
String city;
String state;
Integer pincode;
Customer customer;
Address.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=”entities.Address” table=”ADDRESS”>
<id name=”addressId” type=”long” column=”address_id” >
<generator/>
</id>
<property name=”addressLine1″>
<column name=”address_line1″ />
</property>
<property name=”addressLine2″>
<column name=”address_line2″ />
</property>
<property name=”city”>
<column name=”city” />
</property>
<property name=”state”>
<column name=”state” />
</property>
<property name=”pincode”>
<column name=”pincode” />
</property>
</class>
</hibernate-mapping>
Customer.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=”entities.Customer” table=”CUSTOMER”>
<id name=”customerId” type=”long” column=”customer_id” >
<generator/>
</id>
<property name=”name”>
<column name=”NAME” />
</property>
<property name=”emailAddress”>
<column name=”email_id” />
</property>
<property name=”contactNo”>
<column name=”contact_no” />
</property>
Point to note here is the Many-to-one tag. We are associating the entities with one-to-
one but we are using a many-to-one tag. When using many-to-one in one-to-one
mapping, we ignore the ‘many’ part. We are not caring how many address are bound
to a customer, but here we ensure that only one customer (to-one part) is bound to an
address.
Address address;
(As its not a List/Set or collection) we ensure that its just an one-to-one relationship.
// save customer
Customer customer = new Customer();
customer.setName(“Surya”);
customer.setEmailAddress(“[email protected]“);
customer.setContactNo(“91-932686876″);
Address address = new Address();
address.setAddressLine1(“xxx-street, near Surya Complex”);
address.setCity(“Pune”);
address.setState(“Maharashtra”);
address.setPincode(11111);
customer.setAddress(address);
address.setCustomer(customer);
session.save(customer);
This article describes how a Primary key One-to-one association can be done.
Consider a Customer and address entities. Each customer will have one address. And
an address is associated with one customer. To make this relationship work in
database customer and address will have same Id(primary key). Mapping this kind of
relationship in Hibernate is called primary key One-to-One association. Doing so will
help you saving, updating, deleting related entities easy.
Here both customer and address share same primary key. Address_id is primary key
and also a foreign key. Any new address should belong to a some customer. Customet
ID will be an autogenerated sequence in database. But Address ID shuld be copied
from customer table.
Customer.java Address.java
Customer.java bean has the following fields and their getter and setter methods:
long customerId;
String name;
String emailAddress;
String contactNo;
Address address;
And Address.java bean has follow following fields and their getter and setter
methods:
long addressId;
String addressLine1;
String addressLine2;
String city;
String state;
Integer pincode;
Customer customer;
<?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=”entities.Customer” table=”CUSTOMER”>
<id name=”customerId” type=”long” column=”customer_id” >
<generator/>
</id>
<property name=”name”>
<column name=”NAME” />
</property>
<property name=”emailAddress”>
<column name=”email_id” />
</property>
<property name=”contactNo”>
<column name=”contact_no” />
</property>
<one-to-one name=”address”
cascade=”all”
>
</one-to-one>
</class>
</hibernate-mapping>
Important part is the one-to-one mapping. Name should point to the Address type
variable defined in Customer entity.
We have cascade =“all”. This means both the entities are related in all the
operations.Adding / updating and deleting Customer will also do same on related
address entity.
<?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=”entities.Address” table=”ADDRESS”>
<id name=”addressId” type=”long” column=”address_id” >
<generator>
<param name=”property”>customer</param>
</generator>
</id>
<property name=”addressLine1″>
<column name=”address_line1″ />
</property>
<property name=”addressLine2″>
<column name=”address_line2″ />
</property>
<property name=”city”>
<column name=”city” />
</property>
<property name=”state”>
<column name=”state” />
</property>
<property name=”pincode”>
<column name=”pincode” />
</property>
<one-to-one name=”customer”
constrained=”true” />
</class>
</hibernate-mapping>
1. Address table do not have any ID generation strategy. It has to get id from
customer table.
2. The Address ID is a foreign key which should be specified to hibernate.
This is to ensure the order of insert/delete and update statements, which hibernate
would perform on these two tables.
Now the mapping part is over. We can test it using following client code:
-------------------------------------------------------------------------------------------------------
----------------------------------------------
package entities;
import java.io.Serializable;
public class PurchasedTestId implements Serializable{
private Long testId;
private Long customerId;
// an easy initializing constructor
public PurchasedTestId(Long testId, Long customerId){
this.testId = testId;
this.customerId = customerId;
}
public Long getTestId() {
return testId;
}
public void setTestId(Long testId) {
this.testId = testId;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
@Override
public boolean equals(Object arg0) {
if(arg0 == null) return false;
if(!(arg0 instanceof PurchasedTestId)) return false;
PurchasedTestId arg1 = (PurchasedTestId) arg0;
return (this.testId.longValue() == arg1.getTestId().longValue()) &&
(this.customerId.longValue() == arg1.getCustomerId().longValue());
}
@Override
public int hashCode() {
int hsCode;
hsCode = testId.hashCode();
hsCode = 19 * hsCode+ customerId.hashCode();
return hsCode;
}
}
2 main things to note here are:
1. the Class implements Serializable
2. The equals() and hashcode() functions. It is important to implement these 2
functions as hibernate relies on these methods to cache and compare the data.
So with this ID class, the PurchasedTest bean representing tests_purchased table
would look like below:
package entities;
import java.util.Date;
public class PurchasedTest {
PurchasedTestId purchasedTestId;
Date purchaseDate;
Here it replaces both testId and customerId columns and declares single
purchasedTestId variable.
<?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=”entities.PurchasedTest” table=”tests_purchased”>
<composite-id name=”purchasedTestId”>
<key-property name=”testId” column=”TEST_ID” />
<key-property name=”customerId” column=”CUSTOMER_ID” />
</composite-id>
The <id> is replaced by <composite-id> tag. The name filed specifies the name of the
PurchasedTestId type property in PurchasedTest bean.
Both the <key-property> tags represent the key columns.
With the above setting one can do operations on tests_purchased table like below:
// To save data
session.delete(ptest);
I have seen people using saveOrUpdate() instead of an update. Hibernate doc clearly
says that update() or saveOrUpdate() is to be used in the following scenario:
In hibernate mapping file the <class> element maps the domain object with
corresponding entity in the database. It will be defined under <hibernate-mapping>
tag. <Hibernate-mapping> tag also allows multiple <class> tags inside it. (i.e we can
save multiple class mapping information in a single file).
<hibernate-mapping>
<id column=”user_task_id”>
<generator>
</generator>
</id>
</class>
</hibernate-mapping>
Here we don’t discuss all the class element attributes, but some which I found very
useful:
Hibernate actually generates SQL statements for each <class> element when startup.
(The statements like select, update delete statements). The UPDATE statement
generated will by default update all the columns. So when there is any change is
single column by default all the columns will be updated. This can be problem if the
table is big. Same with insert statements also.
We can turn this feature off and ask the hibernate not to generate dynamic insert and
update statements. We can do this by specifying the dynamic-insert=”true” and
dynamic-update=”true”.
If you want to do in using annotaions then, you can mark the class with following
annotation (below @Entity annotation):
@org.hibernate.annotations.Entity(
dynamicInsert=true, dynamicUpdate=true
This deals with the detached objects. We fetch entity data using session or persistent
context. The entities will be normal bean if they are not inside a persistent context or
session. Session gets open and when you select, or fetch, the resulted entity object
becomes attached. I.e any chages done to entity obect will also effect its database
status. But once the persistencecontext is closed or the session is closed, the objects
become detached. Changes made to it donot effect corresponding table. So to save the
change done to detached entity, we need to reattach it and merge changes, by calling
update().
Contact.setLastname(“Rao”);
Transaction tx = sess.beginTransaction();
Sess.update(contact);
Contact.setPhonenumber(“234234-234234);
Contact.setAddress(“sg jasgd ajsdg “);
Tx.commit();
Here when update() called, the entity got attached again. This always issues an
UPDATE statement. This happens irrespective of weather the object has changed
after detaching or not. One way to avoid this UPDATE statement while reattaching is
setting the select-before-update= “true”. If this is set, hibernates tries to determine if
the UPDATE needed by executing the SELECT statement.
In annotations:
@org.hibernate.annotations.Entity(selectBeforeUpdate=true)
3. mutable (default value= true, optional) : by setting a classs mutable you can tell
hibernate that there will be no UPDATE statement will ever be needed for the table.
This prevents the Hibernate to do dirty checking(checking if any row has changed)
and Hibernate can optimize itself.
In annotations:
@org.hibernate.annotations.Entity(Mutable=false)
Once your dynamic site has gone bigger, data in relational database
has grown, there is always a need for searching the contents. SQL queries with like
‘%…%’ are useful. But to do multiple columns / table searching, we’ll need to have
big SQL queries with different conditions, ANDed and ORed. Such searching is not
realistic and can not be maintained and extended easily.
For Hibernate users, Hibernate search helps searching rows from database. Without
writing any complex SQL queries, you can search multiple columns and get related
objects from db.
In our site Skill-Guru , you will notice a search box on the right hand side. We have
enabled the search on few tables and columns initially. Currently it will search for the
tests , description and keywords for the input keyword.
Hibernate search searches objects from text queries. It uses Apache Lucene Indexing
technique. It indexes the tables with the help of annotations. Also it does the
synchronization of database and index. Following tutorial demonstrates a simple
searching example using hibernate search. The application uses JPA way.
Consider any site selling some products. You want to search products by title,
description etc. Consider following products table.
<persistence-unit name=”defaultManager”
transaction-type=”RESOURCE_LOCAL”>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name=”hibernate.connection.driver_class”
value=”com.mysql.jdbc.Driver” />
<property name=”hibernate.connection.url”
value=”jdbc:mysql://localhost:3306/hibernatetest” ></property>
<property name=”hibernate.connection.username” value=”root” />
<property name=”hibernate.connection.password”
value=”root” />
<property name=”hibernate.show_sql” value=”false” />
<property name=”hibernate.search.default.directory_provider”
value=”org.hibernate.search.store.FSDirectoryProvider” />
<property name=”hibernate.search.indexing_strategy” value=”manual” />
<property name=”hibernate.search.default.indexBase” value=”e:\indexes” />
</properties>
</persistence-unit>
</persistence>
Make sure you have database url, username and password entered properly. Another
important factor is the indexBase directory. Hibernate search creates indexes for each
table it need to search and those indexes will be saved in this directory.
The properties:
<property name=”hibernate.search.default.directory_provider”
value=”org.hibernate.search.store.FSDirectoryProvider” />
<property name=”hibernate.search.indexing_strategy” value=”manual” />
<property name=”hibernate.search.default.indexBase” value=”e:\indexes” />
are used by Hibernate Search.
Create test.eo package and create a ProductEO class. The ProductEO entity class for
products table might look like below:
Create test.eo package and create a ProductEO class. The ProductEO entity class for
products table might look like below:
package test.eo;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name=”product”)
public class ProductEO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name=”id”)
private Integer id;
@Column(name=”title”)
private String title;
@Column(name=”description”)
private String description;
@Column(name=”manufacture_date”)
private Date manifactureDate;
To make this entity to be able to be searched, we need to add some more annotations.
Altered Entity class is shown below:
package test.eo;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
@Entity
@Table(name=”product”)
@Indexed
public class ProductEO {
@DocumentId
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name=”id”)
private Integer id;
@Field(index=Index.TOKENIZED, store=Store.NO)
@Column(name=”title”)
private String title;
@Field(index=Index.TOKENIZED, store=Store.NO)
@Column(name=”description”)
private String description;
@Column(name=”manufacture_date”)
private Date manifactureDate;
We added following:
package test.services;
import javax.persistence.*;
public class HibernateEntitymanagerHelper {
private static EntityManagerFactory emf;
static{
try{
emf = Persistence.createEntityManagerFactory(“defaultManager”);
}catch(Throwable tw){
throw new ExceptionInInitializerError(tw);
}
}
public static EntityManagerFactory getEntityManagerFactory() {
return emf;
}
public static void shutdown() {
emf.close();
}
}
Create following AddProducts class in test.services package and add some data into
the table:
package test.services;
import javax.persistence.EntityManager;
import test.eo.*;
import java.util.Date;
em.persist(prodEO);
em.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
}
}
}
Now, this is time to test. For Hibernate search to work you have to trigger an initial
Indexing to populate the Lucene index with the data already present in your database.
Following code creates indexes and then does searching.
package test.services;
import java.util.List;
import javax.persistence.EntityManager;
import test.eo.*;
import java.util.Date;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;
/**
* @param args
*/
public static void main(String[] args) {
try{
EntityManager em =
HibernateEntitymanagerHelper.getEntityManagerFactory().createEntityManager();
FullTextEntityManager fullTextEntityManager =
Search.getFullTextEntityManager(em);
fullTextEntityManager.getTransaction().begin();
/*
* Search only by lowercase
*/
org.apache.lucene.search.Query query = parser.parse( “phone” );
// wrap Lucene query in a javax.persistence.Query
javax.persistence.Query persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, ProductEO.class);
// execute search
List<ProductEO> result = persistenceQuery.getResultList();
System.out.println(“result ::”+result);
for (ProductEO product : result) {
System.out.println(“product ::”+product.getTitle());
}
fullTextEntityManager.getTransaction().commit();
em.close();
HibernateEntitymanagerHelper.shutdown();
}catch(Exception e){
e.printStackTrace();
}
Going for an interview or want to test your hibernate skills , check out our hibernate
interview questions
In this post we will talk about how to integrate hibernate Search into
your existing Spring, JPA and Hibernate application and some of the challenges we
faced.
We have a web application using Hibernate (with JPA ) and Spring. This application
relies on Spring for transaction, bean initialization / injection etc. EntityManager,
transaction are configured in application.xml file. When integrating Hibernate search
in such an application one might face problems. In this post I am sharing some
problems I faced during integration and the solutions for same.
Spring configuration:
<bean id=”propertyConfigurer”>
<property name=”location” value=”classpath:myproperties.properties”/>
</bean>
<bean id=”entityManager”
p:dataSource-ref=”dataSource”>
<property name=”persistenceUnitName” value=”defaultManager” />
<property name=”jpaVendorAdapter”>
<bean>
<property name=”database” value=”${jpa.database}”/>
<property name=”showSql” value=”${jpa.showSql}”/>
</bean>
</property>
</bean>
<bean id=”transactionManager”
p:entityManagerFactory-ref=”entityManager”/>
In the base DAO, I have entityManager as class level variable, value to which will
be injected by spring:
@PersistenceContext(unitName = “defaultManager”)
private EntityManager entityManager;
For Hibernate search we need FullTextEntityManager. This instance of
FullTextEntityManager will be created using entityManager as below:
fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
FullTextEntityManager fullTextEntityManager;
public abstractDAO(){
super();
@PostConstruct
public void setPersistenceUnit(){
super.setUnit(entityManager);
fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
My initial action was to look into index directory to see if they are being created. It
looked perfectly ok there.
The problem was, search operation was not getting transaction while searching. The
spring was not injecting transaction into a fullTextEntityManager created from
entityManager.
and search started working!! But this gave me other problems. Any changes to the
entity bean got saved into DB without even committing!!!! I had to revert this change.
After a lot of tries and searching, just changing my DAO code solved this. Instead of
making FullTextEntityManager a class level variable, I instatiated it from
entityManager whenever I wanted to search. Something like below:
@PersistenceContext(unitName = “defaultManager”)
private EntityManager entityManager;
public abstractDAO(){
super();
}
@PostConstruct
public void setPersistenceUnit(){
super.setUnit(entityManager);
This is third hibernate tutorial for advanced users .We will talk about
hibernate persistence and how you will connect with hibernate to the database. The
database we would be using is mysql.
Our last two posts had covered hibernate setup , hibernate configuration and how
using annotation with hibernate.
mysql-connector.jar
ejb3-persistence.jar, antlr-2.7.6.jar
asm.jar
asm-attrs.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
concurrent-1.3.2.jar
connector.jar
dom4j-1.6.1.jar
ehcache-1.2.3.jar
hibernate3.jar
hibernate-annotations.jar
hibernate-entitymanager.jar
hibernate-tools.jar
jaas.jar
jacc-1_0-fr.jar
javassist.jar
jaxen-1.1-beta-7.jar
jboss-cache.jar
jboss-common.jar
jboss-jmx.jar
jboss-system.jar
jdbc2_0-stdext.jar
jgroups-2.2.8.jar
jta.jar
log4j-1.2.11.jar
oscache-2.1.jar
proxool-0.8.3.jar
swarmcache-1.0rc2.jar
syndiag2.jar
xerces-2.6.2.jar
xml-apis.jar
Step 3:
Com.myapp.vo this package will contain all the beans for Entity Classes.
DB Setup:
package com.myapp.accessor;
package com.myapp.vo;
import com. myapp.accessor.User;
Integer userId;
String userName;
String password;
Byte state;
return userId;
this.userId = userId;
return userName;
this.userName = userName;
return password;
this.password = password;
this.state = state;
package com.myapp.eo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.jda.server.accessor.User;
import com.jda.server.vo.UserVO;
@Entity
@Table(name=”users”)
User user;
@Transient
return user;
}
this.user = user;
public UserEO(){
this.user = user;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
return user.getUserId();
user.setUserId(userId);
@Column(name=”username”)
return user.getUserName();
user.setUserName(userName);
}
@Column(name=”password”)
return user.getPassword();
user.setPassword(password);
@Column(name=”state”)
return user.getState();
user.setState(state);
“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>
<hibernate-configuration>
<session-factory>
<property name=”connection.url”>jdbc:mysql://localhost/myapp_db</property>
<property name=”connection.username”>root</property>
<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”connection.password”>root</property>
<property
name=”transaction.factory_class”>org.hibernate.transaction.JDBCTransactionFactory
</property>
<property name=”current_session_context_class”>thread</property>
<property name=”hibernate.show_sql”>true</property>
<mapping package=”com.myapp.eo”/>
<mapping class=”com.myapp.eo.UserEO”/>
</session-factory>
</hibernate-configuration>
Now in Hibernate for every database operation you will need a hibernate session.
Now we have entity mapping and we have also configured the db. Now we need
hibernate session to
cfg.addAnnotatedClass(Contact.class);
cfg.configure();
session =sessionFactory.openSession();
But it is not practical for the entire bean to open multiple sessions to same db for
multiple operations. In a complex application you might have number of tables for
which you will have number of beans to update/execute query. So it’s important to
make sure all your application share a single session object.
We can accomplish this using a Singleton design pattern. Create a static session object
and initialize it in the static block. This ensures that the session will be open before
anyone tries to access session object. The class can look something like this:
package com.myapp.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
private HibernateSessionUtil() {
static{
return sessionFactory;
return sessionFactory.openSession();
return sessionFactory.getCurrentSession();
if (sessionFactory != null)
sessionFactory.close();
sessionFactory = null;
We will also define exceptions which our application might throw. This are the
application exceptions, part of business logic. For example in our application if we
want to verify a user’s username ans pwd, then if the user is not found , we can throw
a UserNotFound exception. If user’s password is not matching we can thorw a
UserException with message the password didn’t match. If there is any other
(checked) exception the system will wrap it inside a MyAppException and throw it.
package com.myapp.exception;
super(msg);
super(msg, cause);
package com.myapp.exception;
super(msg);
super(msg, cause);
}
package com.myapp.exception;
super(msg);
super(msg, cause);
Now we need functions for db operations. We do it in the service classess. For each
business requirement we can have a service function which will perform the required
task and return the results back. An example for user table business actions is shown
below. It shows simple select, create and update and delete functions.
package com.myapp.service;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.myapp.accessor.*;
import com.myapp.eo.*;
import com.myapp.vo.*;
import com.myapp.hibernate.*;
import com.myapp.exception.MyAppException;
import com.myapp.exception.UserException;
import com.myapp.exception.UserNotFoundException;
Transaction tx = null;
try {
tx = session.beginTransaction();
q.setParameter(“userName”, user.getUserName());
if(users.size() < 1)
if(!user.getPassword().equals(userVO.getPassword()))
else
user = userVO;
}
tx.commit();
} catch (Exception e) {
try {
tx.rollback();
return user;
Transaction tx = null;
try {
tx = session.beginTransaction();
userEO = (UserEO)session.merge(userEO);
userObj = userEO.getUser();
tx.commit();
} catch (Exception e) {
try {
tx.rollback();
return userObj;
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete(userEO);
tx.commit();
} catch (RuntimeException e) {
tx.rollback();
package com.myapp.client;
import com.myapp.service.*;
import com.myapp.vo.*;
import com.myapp.accessor.*;
user.setUserName(“Alex”);
user.setPassword(“XXX”);
try{
}catch(Exception e){
e.printStackTrace();
user.setUserName(“Smitha2″);
user.setPassword(“XXX”);
user.setState((byte)1);
try{
svdUser = service.createUpdateUser(user);
}catch(Exception e){
e.printStackTrace();
System.out.println(“svdUser.getUserId() ==>”+svdUser.getUserId());
svdUser.setPassword(“YYY”);
try{
svdUser = service.createUpdateUser(svdUser);
}catch(Exception e){
e.printStackTrace();
try{
service.deleteUser(svdUser);
}catch(Exception e){
e.printStackTrace();
I hope that this hibernate tutorial would be helpful to you. Please let us know your
comments and feedback
In case you missed the first post Hibernate Tutorial for beginners ,
please go through it if you are new to hibernate.
Annotations are powerful and easy way used to provide metadata about the class.They
do not effect the operation of the code. They can be used to provide information about
the class to the compiler. They can be used to replace the configuration files. Many
applications scan files and detect annotated classes and get configured accordingly. I
am using JPA API here to demonstrate you the usage of annotations. Please
download ejb3-persistence.jar and include in your referenced libraries.
We do not need jboss to run JPA hibernate examples but we can copy these jar files in
our webserver and we are good to go.
I hope you have gone through my previous post explaining how to configure and run
the first hibernate example because this hibernate tutorial would cover the next steps.
There I have used Conatct.hbm.xml file to map the Contact class to the contact
table. Below I have explained how we can use annotations to replace the table
hbm.xml files in Hibernate.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.*;
@Entity
@Table(name=”contact”)
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
@Column(name=”FIRSTNAME”)
public String getFirstName() {
return firstName;
}
@Column(name=”LASTNAME”)
public String getLastName() {
return lastName;
}
@Column(name=”EMAIL”)
public String getEmail() {
return email;
}
public void setEmail(String string) {
email = string;
}
@Id
@Column(name=”ID”)
public long getId() {
return id;
}
@Entity
@Table(name=”contact”)
annotations.
@Entity declares the class as an entity bean. @Table annotation specifies compiler
that the table name in db is ‘contact’. If @Table is not specified, then the classname
will be considered as table name.
@Column specifies the column name of the table. We specify it for the getter method
of the field. If not specified, the field name itself is considered as the column name.
Each table should have a primary key. This will be specified by @Id annotation.
Now we can test the above configuration using the client class as follows:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
//Create new instance of Contact and set values in it by reading them from form object
System.out.println(“Inserting Record”);
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName(“Smitha”);
contact.setLastName(“Rao”);
contact.setEmail(“[email protected]“);
session.save(contact);
System.out.println(“Done”);
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
Run MyExample file.
Output would be :
log4j:WARN No appenders could be found for logger
(org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into contact (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?,
?, ?)
I hope you would be enjoying these hibernate tutorial. Please give us your feedback.
http://www.skill-guru.com/blog/2009/08/05/first-hibernate-tutorial-%E2%80%93get-
hands-on-experience/