Monday, August 26, 2013

Hibernate Day3.. Simple Hibernate Example With Annotations


I am going to explain with simple... Friend class.


@Entity
public class Friend {
    @Id @GeneratedValue
    private int fid;
    private String fname;
    private String lname;


1)First thing you have to do is mark your class with @Entity
2)The class name will be taken as default table name in to which Friend object is going
   to be stored.We can override the default with other annotations.We will see it later.
   Property names becomes the column names in the table.We can override default
   and specify the new columnname in to which we need hibernate to store the values.
3)You have to annotate the property which acts as your primary key with @Id annotation. In the above
   example I have marked fid as my primary key.
4)@GeneratedValue means while saving friend we don't provide fid in to the object,
   hibernate helps us in generating a unique primary and sets in to the table.

5)Here is the new hibernate.cfg.xml.Only change you observe is the mapping element.
Instead of specifying the hbm files, we have to specify the classes which are
annotated.

<?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="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
    <property name="hibernate.connection.username">hr</property>
    <property name="hibernate.connection.password">hr</property>
    <property name="hibernate.hbm2ddl.auto" >update</property>
    <property name="hibernate.show_sql">true</property>
    <mapping class="annotationspkg.Friend"/>
   
  </session-factory>
</hibernate-configuration>

6)Instead of Configuration object, you need to use AnnotationConfiguration object.
   AnnotationConfiguration has the ability to read the classes annotated with the
  annotations.

7)Run the main method in Friend.java to test the annotations example

Imp Note:

In the example I uploaded I used AnnotationConfiguration but from hibernate3.6,we
can use.. Configuration itself as it has been enhanced to understand... annotations.

AnnotationConfiguration is deprecated from 3.6 release....


 Uploaded the example in the following URL

https://docs.google.com/file/d/0BwZaaDwCofcNZFlWTlFBS3lFZ00/edit?usp=sharing











No comments:

Post a Comment