Share |
Print

Hibernate Introduction with Annotation

Before Java 5, Hibernate has XML way of configuring things. However with introduction of Annotations?, the world has changed a lot. Many frameworks has adopted annotations as an alternative to XML. Hibernate has also adopted annotation. The XML way is still supported but annotation is the predominant way of working now. We will do the same example as we did in Hibernate Introduction using annotation.

Download the Hibernate Core and Hibernate Annotations from https://www.hibernate.org/6.html(external link). Let's make a Java project and pull the following libraries.
From Hibernate Core (<hibernate-distribution-*>/lib/required)
  • antlr-2.7.6
  • commons-collections-3.1.jar
  • dom4j-1.6.1.jar
  • hibernate3.jar
  • javassist-3.9.0.GA.jar
  • jta-1.1.jar
  • slf4j-api-1.5.8.jar
  • <hibernate-distribution-*>/lib/ -Choose between cglib or javassist

From Hibernate Annotation:
  • lib/ejb3-persistence.jar
  • lib/hibernate-commons-annotations.jar
  • hibernate-annotations.jar

Download slf4j from http://www.slf4j.org/(external link)
  • slf4j-simple-1.5.8.jar

Hypersonic:
  • hsqldb.jar - We will be using hypersonic database for this example. you need to download hypersonic jar. For details see Hypersonic.

Now let's write our domain class which is Student class.
Student
//Entity annotation represents that it is an entity class and is //mapped to a table in database. Table annotation tells about the //table name to which this entity is mapped @Entity @Table(name="Student") public class Student { //Id will correspond the primary key in the database private Long id; protected String name; //Id - Represents that it is a primary key column //GeneratedValue - How the key to be generated //column - Column to which this property is mapped @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="STUDENT_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } //There is annotation here so by default it is mapped to //the column with name NAME. In annotation, the properties are //by default mapped. In XML mapping by default the columns //are not mapped. public String getName() { return name; } public void setName(String name) { this.name = name; } }


If you have done the Hibernate Introduction, you will realize that the mapping has been pulled in the class file itself in terms of annotations. The parallel can easily be drawn. Also now we do not need any mapping hbm.xml file. We still need the configuration XML, though the mapping will be done by referencing to class
hibernate.cfg.xml (Put it in the class path)
<?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> <!-- Database connection settings --> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect - This tells the SQL grammer to be used --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Log out all the sql that hibernate is issuing to datbase. This is very useful for debugging --> <property name="show_sql">true</property> <!-- validates the table structure as per mapping definition. --> <property name="hbm2ddl.auto">validate</property> <!-- Mapping class. --> <mapping class="com.oyejava.Student"/> </session-factory> </hibernate-configuration>


Let's write the Hibernate util class which is a utility class to make the Hibernate session factory. The Session factory at runtime contains all the configuration and mapping details. From Session factory we can get the Session, which is a lightweight object and helps us in interacting with the database. Session can be thought of as a Connection as in JDBC thought the Session may choose to not to open the connection to the database.
HibernateUtil
public class HibernateUtil { private static SessionFactory sessionFactory; static{ try{ //By default it will look for hibernate.cfg.xml in the class path sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory(); }catch(Throwable ex){ throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void shutdown(){ //Close caches and connection pool getSessionFactory().close(); } }

Now in the application logic, in this case in the main method we can create a Student object and save it to the database.
public class HibernateBasic { public static void main(String[] args) { //Get the session from the Session factory Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx= session.beginTransaction(); Student student = new Student(); student.setName("oyeJava"); Long studentId = (Long)session.save(student); System.out.println(studentId); tx.commit(); session.close(); } }

Those who have done the hibernate in the XML way will notice that the only difference the two has got is in terms of where the mapping is kept. You can download the source code from the attachment section down below.


Back to Hibernate Index
Back To Java Home
Back To Home

List of attached files
 id Name   desc uploaded Size Downloads
1 4 zip HibernateAnnotation.zip View Download   Hibernation Annotation Example Mon 22 of June, 2009 11:26 IST by lalit 3.02 Kb 250

Post new comment

Click for Help
BoldItalicUnderlineStrikethroughExternal LinkSmileys
Anti-Bot verification code: Random Image
Post new comment