Hibernate Tutorial – Using Annotations with Hibernate
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(“smithaxxx@yahoo.com“);
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.









jpa tutorial on http://www.jaiswaltraining.com\jpa is also very good. It gives jpa crud application example along with web jpa and ejb jpa on tomcat, glassfish and websphere.
jpa on myeclipse can also be found
Good
In the example to make the tutorial simple, I have used Hibernate’s AnnotationConfiguration to load the entity class . With following code :
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(Contact.class);
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
I am loading the entity class in the code. Using persistence.xml and EntityManager of JPA, you can make the entity classes to get loaded automatically when entityManager is loaded or even when application starts.
Hey .. Nice one for learn JPA beginner.
I saw the tutorial for JPA, in that they used one file “persistent.xml”.
I am just little confuse why we are not using that file here.