0% found this document useful (0 votes)
318 views

One-to-One Mapping in Hibernate Using Foreign Key Association

1. The document discusses one-to-one mapping in Hibernate using foreign key association. In this mapping, two entities have a one-to-one relationship using foreign keys, with one table holding the primary key of the other. 2. As an example, the Customer table contains an address_id column storing the primary key of the associated Address. The tables and entity classes are defined along with the corresponding Hibernate mapping files. 3. The mapping uses a many-to-one association in the Customer mapping despite it being a one-to-one relationship, ignoring the 'many' aspect. This ensures each customer is associated with only one address.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
318 views

One-to-One Mapping in Hibernate Using Foreign Key Association

1. The document discusses one-to-one mapping in Hibernate using foreign key association. In this mapping, two entities have a one-to-one relationship using foreign keys, with one table holding the primary key of the other. 2. As an example, the Customer table contains an address_id column storing the primary key of the associated Address. The tables and entity classes are defined along with the corresponding Hibernate mapping files. 3. The mapping uses a many-to-one association in the Customer mapping despite it being a one-to-one relationship, ignoring the 'many' aspect. This ensures each customer is associated with only one address.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 45

http://www.skill-guru.

com/blog/2010/02/10/mapping-composite-keys-in-hibernate/

One-to-One mapping in Hibernate using Foreign Key


Association
February 16th, 2010 smitha Leave a comment Go to comments

One-to-One mapping can be done in 2 ways:

1. Primary key association:


2. Foreign key association.

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.

The tables would look like below:

create table address(


    address_id int(11) not null auto_increment,
    address_line1 varchar(100) not null,
    address_line2 varchar(100),
    city varchar(50) not null,
    state varchar(50) not null,
    pincode int(10) not null,
    primary key(address_id));

create table customer(


    customer_id int(11) not null auto_increment,
    name varchar(50) not null,
    email_id varchar(100),
    contact_no varchar(20),
    address_id int(11),
    primary key(customer_id),
    foreign key(address_id) references address(address_id));

 
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:

public class Address {

 long addressId;
 String addressLine1;
 String addressLine2;
 String city;
 String state;
 Integer pincode;
 Customer customer;

public class Customer {


 Long customerId;
    String name;
    String emailAddress;
    String contactNo;
    Address address;

The Hibernate mapping files would look like below:

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>

address.hbm.xml is simple and there is no much complications.

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>

    <many-to-one name=”address”


                column=”address_id”
                cascade=”all”  unique=”true”
                />
  </class>
</hibernate-mapping>
 

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.

In customer class, by defining the address variable as below:

 Address address;

 (As its not a List/Set or collection) we ensure that its just an one-to-one relationship.

 Now we can test it using following code:

// 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);

   //fetch all customers


           
            Query query = session.createQuery(“from Customer customer”);
            for(Iterator it=query.iterate();it.hasNext();){
             Customer customer1 = (Customer) it.next();
             Address address1 = customer1.getAddress();
                System.out.println(“customer ID: ” + customer1.getCustomerId());
                System.out.println(“Name: ” + customer1.getName());
                System.out.println(“address: ” + address1.getAddressLine1());
                System.out.println(address1.getAddressId());
                System.out.println(address1.getAddressLine2());
                System.out.println(address1.getCity());
                System.out.println(address1.getState());
                System.out.println(address1.getPincode());
              }

One-to-one mapping in hibernate


In Hibernate One-to-One mapping can be done in 2 ways: 

1. Primary key association:


2. Foreign key association. 

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.

 Define following 2 tables in mysql database.

create table customer(


    customer_id int(11) not null auto_increment,
    name varchar(50) not null,
    email_id varchar(100),
    contact_no varchar(20),
    primary key(customer_id));

 create table address(


    address_id int(11) not null,
    address_line1 varchar(100) not null,
    address_line2 varchar(100),
    city varchar(50) not null,
    state varchar(50) not null,
    pincode int(10) not null,
    primary key(address_id),
    foreign key(address_id) references customer(customer_id));

 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.

Now lets define the entities:

Customer.java   Address.java

(you can download full code at the end of the article)

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;

In One-to-One primary key mapping, we need to relate both the entities


bidirectional.We need to have address property in customer and vice versa. 

Lets define the hibernate mapping files:

 customer.hbm.xml file will look like below:

<?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.

 address.hbm.xml file will look like below:

<?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>

In this mapping file we have to ensure 2 things:

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.

 <id name=”addressId” type=”long” column=”address_id” >


   <generator>
        <param name=”property”>customer</param>
   </generator>
</id>
Is to ensure that the addresseId gets a value of customerId we use special id
generation strategy called “foreign”.

To specify the foreign key constraint on addressId, we have set constrained=”true” 


like below in address.hbm.xml file

<one-to-one name=”customer”constrained=“true” />

  

Now the mapping part is over. We can test it using following client code:

// saving the Customer and Address data

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);
//Fetch all the customers
Query query = session.createQuery(“from Customer customer”);
for(Iterator it=query.iterate();it.hasNext();){
 Customer customer1 = (Customer) it.next();
 Address address1 = customer1.getAddress();
 System.out.println(“customer ID: ” + customer1.getCustomerId());
 System.out.println(“Name: ” + customer1.getName());
 System.out.println(“address: ” + address1.getAddressLine1());
 System.out.println(address1.getAddressLine2());
 System.out.println(address1.getCity());
 System.out.println(address1.getState());
 System.out.println(address1.getPincode());
}

// delete a customer – also delete address


Query query = session.createQuery(“from Customer customer where
customer.customerId = :cust”).setLong(“cust”, 3);
            Customer customer2 = (Customer) query.uniqueResult();
session.delete(customer2);

// delete only Address


Query query = session.createQuery(“from Customer customer where
customer.customerId = :cust”).setLong(“cust”, 1);
Customer customer2 = (Customer) query.uniqueResult();
Address address2 = customer2.getAddress();
customer2.setAddress(null);
address2.setCustomer(null);
session.delete(address2);

 -------------------------------------------------------------------------------------------------------
----------------------------------------------

Mapping Composite Keys in Hibernate


February 10th, 2010 smitha Leave a comment Go to comments

In Real world applications it is natural to have tables with composite


keys. The row will be identified with combination of key  column values of a row.

Consider Following scenario:

A test selling website defines tests and customers.

create table test(


test_id int(11) not null auto_increment,
test_name varchar(100),
test_desc varchar(150),
test_questions varchar(5),
primary key(test_id));

create table customer(


customer_id int(11) not null auto_increment,
name varchar(50) not null,
email_id varchar(100),
contact_no varchar(20),
primary key(customer_id));

To keep track of tests purchased by customers it maintains following table:

create table tests_purchased(


customer_id int(11) not null,
test_id int(11) not null,
created_date datetime not null,
primary key(customer_id, test_id));
Primary key of this table is combination of customer and test id.
To map such classes we have to use <composite-key> tag.  Both the test_id and
customer_id acts as identifier to the tests_purchased table.

In hibernate we use session.load (entityClass, id_type_object) to find and load the


entity using primary key. In case of composite keys, the id object should be a separate
‘id ‘ class (in above case a PurchasedTestId class)  which just declares the primary
key attributes, something like below:

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;

public PurchasedTestId getPurchasedTestId() {


return purchasedTestId;
}
public void setPurchasedTestId(PurchasedTestId purchasedTestId) {
this.purchasedTestId = purchasedTestId;
}
public Date getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(Date purchaseDate) {
this.purchaseDate = purchaseDate;
}

Here it replaces both testId and customerId columns and declares single
purchasedTestId variable.

The purchasedTest.hbm.xml file would look like below:

<?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>

<property name=”purchaseDate” type=”timestamp”>


<column name=”created_date” />
</property>
</class>
</hibernate-mapping>

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

PurchasedTest ptest = new PurchasedTest();


PurchasedTestId purchasedTestId = new PurchasedTestId(1l,1l);
ptest.setPurchasedTestId(purchasedTestId);
ptest.setPurchaseDate(new Date());
session.save(ptest);
// To find data
PurchasedTestId purchasedTestId = new PurchasedTestId(1l,1l);
PurchasedTest ptest = (PurchasedTest)session.load(PurchasedTest.class,
purchasedTestId);
System.out.println(“test ID ::”+ptest.getPurchasedTestId().getTestId());
System.out.println(“cust ID ::”+ptest.getPurchasedTestId().getCustomerId());

// deleting the row


PurchasedTestId purchasedTestId = new PurchasedTestId(1l,1l);
PurchasedTest ptest = (PurchasedTest)session.load(PurchasedTest.class,
purchasedTestId);

session.delete(ptest);

saveOrUpdate Method in Hibernate


October 22nd, 2009 Vinay Leave a comment Go to comments

There is some bit of confusion with hibernate users as to what exactly


saveorUpdate method does . saveOrUpdate is general purpose method that either
saves a transient instance by generating a new identifier or updates/reattaches
the detached instances associated with its current identifier.

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:

 the application loads an object in the first session


 the object is passed up to the UI tier
 some modifications are made to the object
 the object is passed back down to the business logic tier
 the application persists these modifications by calling update() in a second
session
saveOrUpdate() does the following:

 if the object is already persistent in this session, do nothing


 if another object associated with the session has the same identifier, throw an
exception
 if the object has no identifier property, save() it
 if the object’s identifier has the value assigned to a newly instantiated object,
save() it
 if the object is versioned by a <version> or <timestamp>, and the version
property value is the same value assigned to a newly instantiated object,
save() it
 otherwise update() the object

Some useful options in Class element in Hibernate


October 22nd, 2009 smitha Leave a comment Go to comments

Hibernate mapping: the <Class> element: Some useful options

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).

A sample class element looks like below:

<hibernate-mapping>

<class table=”user_tasks” >

<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:

1. dynamic-insert, dynamic-update attributes: these 2 attributes are optional and


defaults to false.

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”.

<calss name=”contact” dynamic-insert=”true” 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

2. select-before-update (optional – defaults to false):

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”);

Session sess = sessionFactory.getSession();

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.

<class name=”contact” select-before-update= “true”> or

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.

<class name=”contact” mutable=”false”> or

In annotations:

You can mark a class by :

@org.hibernate.annotations.Entity(Mutable=false)

Hibernate Search – Getting Started


June 15th, 2010 smitha Leave a comment Go to comments

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.

create table product(


id int(5) not null auto_increment,
title varchar(100) not null,
description varchar(250) not null,
manufacture_date datetime,
primary key(id));
To start with Hibernate Search , you must have hibernate search downloaded.
Download Hibernate search 3.1.1 and Hibernate 3.
Create a java application and add required jars to your build path. Click here to know
exact jars used in this project.

Crate a src/META-INF directory and create a persistence.xml file with following


contents (edit it according to your database parameters)

<?xml version=”1.0″ encoding=”UTF-8″?>


<persistence xmlns=”http://java.sun.com/xml/ns/persistence”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd” version=”1.0″>

<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;

public Integer getId() {


return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getManifactureDate() {
return manifactureDate;
}
public void setManifactureDate(Date manifactureDate) {
this.manifactureDate = 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;

public Integer getId() {


return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getManifactureDate() {
return manifactureDate;
}
public void setManifactureDate(Date manifactureDate) {
this.manifactureDate = manifactureDate;
}
}

We added following:

1. @Indexed annotation to Class


2. @DocumentId annotation on the primary key. Hibernate Search needs to store an id
in the index to ensure index uniqueness for a given entity. This annotation marks that
unique property. In most of the cases this will be the primary key.
3. @Field(index=Index.TOKENIZED, store=Store.NO) annotation on the fields,
which need to be matched while searching. The parameter
index=Index.TOKENIZED will ensure that the text will be tokenized (in short words
will be identified) using the default Lucene analyzer. store=Store.NO is to  ensures
that the actual data will not be stored in the index.

Now define a HibernateEntitymanagerHelper class in package test.services to


initialize persistence context as below:

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;

public class AddProducts {


public static void main(String[] args) {
try{
EntityManager em =
HibernateEntitymanagerHelper.getEntityManagerFactory().createEntityManager();
em.getTransaction().begin();
ProductEO prodEO = new ProductEO();
prodEO.setTitle(“Mike”);
prodEO.setDescription(“XXX company Mike”);
prodEO.setManifactureDate(new Date());
em.persist(prodEO);

prodEO = new ProductEO();


prodEO.setTitle(“Phone”);
prodEO.setDescription(“YYY company Phone”);
prodEO.setManifactureDate(new Date());
em.persist(prodEO);

prodEO = new ProductEO();


prodEO.setTitle(“Microphone”);
prodEO.setDescription(“YYY company Microphone”);
prodEO.setManifactureDate(new 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;

public class ProductService {

/**
* @param args
*/
public static void main(String[] args) {

try{
EntityManager em =
HibernateEntitymanagerHelper.getEntityManagerFactory().createEntityManager();
FullTextEntityManager fullTextEntityManager = 
Search.getFullTextEntityManager(em);

fullTextEntityManager.getTransaction().begin();

List<ProductEO> products = em.createQuery(“select product  from ProductEO as 


product”).getResultList();
for (ProductEO product : products) {
fullTextEntityManager.index(product);
System.out.println(“Product”+product.getTitle());
}

String[] fields = new String[]{“title”, “description”};


MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new
StandardAnalyzer());
// parser.setDefaultOperator(QueryParser.AND_OPERATOR);

/*
* 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

Integrating hibernate search with a Spring and JPA


Application
July 19th, 2010 smitha Leave a comment Go to comments

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.

Entitymanager configuration in my application.xml

Spring configuration:
<bean id=”propertyConfigurer”>
<property name=”location” value=”classpath:myproperties.properties”/>
</bean>

<bean id=”dataSource” destroy-method=”close”>


<property name=”driverClass” value=”${db.driverClass}”/>
<property name=”jdbcUrl” value=”${db.url}”/>
<property name=”user” value=”${db.username}”/>
<property name=”password” value=”${db.password}”/>
<property name=”minPoolSize” value=”2″/>
<property name=”maxPoolSize” value=”8″/>
<property name=”breakAfterAcquireFailure” value=”false”/>
<property name=”acquireRetryAttempts” value=”3″/>
<!– property name=”idleConnectionTestPeriod” value=”300″ –>
<property name=”testConnectionOnCheckout” value=”true”/>
</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);

To make fullTextEntityManager available for search in the DAO class , I creates a


class level variable fullTextEntityManager and  initialized this in @postConstruct
method (after entityManager injection) as below.
@PersistenceContext(unitName = “defaultManager”)
private EntityManager entityManager;

FullTextEntityManager fullTextEntityManager;

public abstractDAO(){
super();

@PostConstruct
public void setPersistenceUnit(){
super.setUnit(entityManager);
fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

public FullTextEntityManager getFullTextEntityManager(){


return fullTextEntityManager;
}
But this approach gave me
org.hibernate.SessionException: Session is closed!
Exception whenever I tried to search.

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.

For a try I introduced EXTENDED persistence context as below:


@PersistenceContext(unitName =
“defaultManager”,type=PersistenceContextType.EXTENDED)
private EntityManager 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.

My second approach to solve this was to configure fullTextEntirtyManager as Spring


bean (as entityManager was configured) so that it can get the transaction.
I couldn’t do it properly as I found no spring’s implementation for
fullTextEntirtyManager bean configuration.

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);

public FullTextEntityManager getFullTextEntityManager(){


FullTextEntityManager fullTextEntityManager;
fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
return fullTextEntityManager;
}
This solved my problem and the search is working perfectly now.

Hibernate Persistence Tutorial: Use Hibernate in


your java applications to access database
August 17th, 2009 smitha Leave a comment Go to comments

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.

First Hibernate Tutorial

Hibernate Using Annotations


 

Step 1:  Create java project in eclipse

Step2: add the required libraries.

 These steps are well explained with screenshots in :

The required jars used in my projects are:

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:

The Directory structure of the application:

I created a following structure:

Com.myapp.eo this package will contain all the Entity Classes.

Com.myapp.vo this package will contain all the beans for Entity Classes.

Com.myapp.accessor this package contains interfaces common to both eo and vo


packages

Com.myapp.hibernate for hibernate utility classes

Com.myapp.services for the beans which will query database

Com.myapp.client the client programs which will call service functions

Com.myapp.exception will contain all the possible exceptions thrown by our


application.
 

Now create database Entity class.

DB Setup:

Create database myapp_db;


Connect myapp_db;

Create a table with following fields:

Create table users values(user_id int(11) auto_increment,


Username varchar(100),
Password varchar(20)),
Status tinyint(1) default 0,
Primary key user_id);

Now for every db table we’ll have 3 files for each:

One in accessor class which is a common interface to both com.myapp.eo and


com.myapp.vo classes. The vo class is a simple java bean. We use this bean in eo
class in setter and getter methods.

Interface: User.java. Add following interface to com.myapp.accessor package.

package com.myapp.accessor;

public interface User {

public Integer getUserId();

public void setUserId(Integer userId);

public String getUserName();

public void setUserName(String userName);

public String getPassword();

public void setPassword(String password);

public Byte getState();

public void setState(Byte state);

File:UserVO.java. Add this to com.myapp.vo package

package com.myapp.vo;
import com. myapp.accessor.User;

public class UserVO implements User{

Integer userId;

String userName;

String password;

Byte state;

public Integer getUserId() {

return userId;

public void setUserId(Integer userId) {

this.userId = userId;

public String getUserName() {

return userName;

public void setUserName(String userName) {

this.userName = userName;

public String getPassword() {

return password;

public void setPassword(String password) {

this.password = password;

public Byte getState() {


return state;

public void setState(Byte state) {

this.state = state;

The UserEO class: Add this to

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”)

public class UserEO implements User{

User user;

@Transient

public User getUser() {

return user;
}

public void setUser(User user) {

this.user = user;

public UserEO(){

user = new UserVO();

public UserEO(User user){

this.user = user;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name=”user_id”, unique=true, nullable=false, insertable=true,


updatable=true)

public Integer getUserId() {

return user.getUserId();

public void setUserId(Integer userId) {

user.setUserId(userId);

@Column(name=”username”)

public String getUserName() {

return user.getUserName();

public void setUserName(String userName) {

user.setUserName(userName);
}

@Column(name=”password”)

public String getPassword() {

return user.getPassword();

public void setPassword(String password) {

user.setPassword(password);

@Column(name=”state”)

public Byte getState() {

return user.getState();

public void setState(Byte state) {

user.setState(state);

Step 4: Configuring Hibernate and creating a hibernate mapping file

I am using mysql DB. Create a file by name hibernate.cfg.xml in the src


directory.

<?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.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>

<!– thread is the short name for org.hibernate.context.ThreadLocalSessionContext


and let Hibernate bind the session automatically to the thread –>

<property name=”current_session_context_class”>thread</property>

<!– this will show us all sql statements –>

<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.

Usually you do this using some code like below:

Now we have entity mapping and we have also configured the db. Now we need
hibernate session to

AnnotationConfiguration cfg = new AnnotationConfiguration();

cfg.addAnnotatedClass(Contact.class);

cfg.configure();

SessionFactory sessionFactory = cfg.buildSessionFactory();

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;

public class HibernateSessionUtil {

private static org.hibernate.SessionFactory sessionFactory;

private HibernateSessionUtil() {

static{

sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

public static SessionFactory getInstance() {

return sessionFactory;

public Session openSession() {

return sessionFactory.openSession();

public Session getCurrentSession() {

return sessionFactory.getCurrentSession();

public static void close(){

if (sessionFactory != null)
sessionFactory.close();

sessionFactory = null;

Now we have the utility function ready.

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.

Add following classes to the com.myapp.exception package.

package com.myapp.exception;

public class MyAppException extends Exception implements java.io.Serializable{

public MyAppException(String msg) {

super(msg);

public MyAppException(String msg, Throwable cause) {

super(msg, cause);

package com.myapp.exception;

public class UserException extends Exception implements java.io.Serializable{

public UserException(String msg) {

super(msg);

public UserException(String msg, Throwable cause) {

super(msg, cause);
}

package com.myapp.exception;

public class UserNotFoundException extends Exception implements


java.io.Serializable{

public UserNotFoundException(String msg) {

super(msg);

public UserNotFoundException(String msg, Throwable cause) {

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.

Creating the service classes.

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;

public class UserService {

public User authenticateUser(User user) throws


UserException,UserNotFoundException,MyAppException{

Transaction tx = null;

Session session = HibernateSessionUtil.getInstance().getCurrentSession();

try {

tx = session.beginTransaction();

Query q =  session.createQuery(“select users from UserEO as users where


users.userName = :userName”);

q.setParameter(“userName”, user.getUserName());

List users = q.list();

if(users.size() < 1)

throw new UserNotFoundException(“User Not found”);

for (Iterator iter = users.iterator(); iter.hasNext();) {

UserEO element = (UserEO) iter.next();

User userVO = element.getUser();

if(!user.getPassword().equals(userVO.getPassword()))

throw new UserException(“Username and password didnot match”);

else

user = userVO;
}

tx.commit();

} catch (Exception e) {

if (tx != null && tx.isActive()) {

try {

// Second try catch as the rollback could fail as well

tx.rollback();

}    catch (HibernateException e1) {

System.out.println(“Error rolling back transaction”);

// throw again the first exception

throw new MyAppException(“Exception while fetching user data”,e);

return user;

public User createUpdateUser(User user) throws MyAppException{

Transaction tx = null;

User userObj = null;

Session session = HibernateSessionUtil.getInstance().getCurrentSession();

try {

UserEO userEO = new UserEO(user);

tx = session.beginTransaction();

userEO = (UserEO)session.merge(userEO);

userObj = userEO.getUser();
tx.commit();

} catch (Exception e) {

if (tx != null && tx.isActive()) {

try {

// Second try catch as the rollback could fail as well

tx.rollback();

} catch (HibernateException e1) {

System.out.println(“Error rolling back transaction”);

// throw again the first exception

throw new MyAppException(“Exception while saving user data”,e);

return userObj;

public void deleteUser(User user) throws MyAppException{

Transaction tx = null;

Session session = HibernateSessionUtil.getInstance().getCurrentSession();

try {

UserEO userEO = new UserEO(user);

tx = session.beginTransaction();

session.delete(userEO);

tx.commit();

} catch (RuntimeException e) {

if (tx != null && tx.isActive()) {


try {

// Second try catch as the rollback could fail as well

tx.rollback();

} catch (Exception e1) {

System.out.println(“Error rolling back transaction”);

throw new MyAppException(“Exception while deleting user data”,e);

The client for this service would be :

package com.myapp.client;

import com.myapp.service.*;

import com.myapp.vo.*;

import com.myapp.accessor.*;

public class UserTest {

public static void main(String[] args) throws Exception{

UserService service = new UserService();

User user = new UserVO();

user.setUserName(“Alex”);

user.setPassword(“XXX”);

try{

User svd = service.authenticateUser(user);

}catch(Exception e){
e.printStackTrace();

//create new user

user = new UserVO();

user.setUserName(“Smitha2″);

user.setPassword(“XXX”);

user.setState((byte)1);

User svdUser = null;

try{

svdUser = service.createUpdateUser(user);

}catch(Exception e){

e.printStackTrace();

if(svdUser!=null && svdUser.getUserId()!=null){

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

Hibernate Tutorial – Using Annotations with


Hibernate
August 6th, 2009 smitha Leave a comment Go to comments

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.

For beginners, the contact table contains following fields:

Create table CONTACT(


ID int(15),
FIRSTNAME varchar(50) ,
LASTNAME varchar(50),
EMAIL varchar(150));

Change the Contact class as follows:

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;
}

public void setFirstName(String string) {


firstName = string;
}

@Column(name=”LASTNAME”)
public String getLastName() {
return lastName;
}

public void setLastName(String string) {


lastName = string;
}

@Column(name=”EMAIL”)
public String getEmail() {
return email;
}
public void setEmail(String string) {
email = string;
}

@Id
@Column(name=”ID”)
public long getId() {
return id;
}

public void setId(long l) {


id = l;
}

Remove following lines from hibernate.cfg.xml


<mapping resource=”contact.hbm.xml”/>

In above class, we have added

@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;

public class MyExample {


public static void main(String[] args) {
Session session = null;

try{
// This step will read hibernate.cfg.xml and prepare hibernate for use

AnnotationConfiguration cfg = new AnnotationConfiguration();


cfg.addAnnotatedClass(Contact.class);
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
session =sessionFactory.openSession();

//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/

You might also like