Hibernate- Hibernate with Annotations

Hibernate - Annotations

The EJB 3 standard annotations are contained in the javax.persistence package, so we import this package.

  • Use annotations in POJO classes. These classes are called Entity Bean Classes

  • No need of xml files

  • We use AnnotationConfiguartion class instead of Configuration class
    Configuration cfg = new AnnotationConfiguartion ();
    
  • From Hibernate 4.x version Configuration is enough for both annotation and xml configuration

  • We have to configure POJO class in hbm.xml

Commonly used Annotations in Hibernate

1.@Entity

  • Annotation marks this class as an entity.

  • We have to place this annotation at the top of class

2.@Table

  • Specifies Table to be connect with this class. If you don’t use @Table annotation, hibernate will use the class name as the table name by default.

  • We have to place this annotation at the top of class.

3.@Id

Every table has a primary key; we can make the data member as Primary Key using @Id annotation.

4.@GeneratedValue

  It will generate the Primary Key/ ID values automatically

5.@Column

  • This Annotation specifies the details of the column for this property or field.

  • If @Column is not specified, property name will be used as the column name by default.

6.@Transient

We can declare the data members which are not have columns in database table

7.@ManyToMany

  • Cascade: Marks this field as the owning side of the many-to-many relationship and cascade modifier specifies which operations should cascade to the inverse side of relationship

  • mappedBy: This modifier holds the field which specifies the inverse side of the relationship

8.@JoinTable

  • Name: For holding this many-to-many relationship, maps this field with an intermediary database join table specified by name modifier

  • joinColumns: Identifies the owning side of columns which are necessary to identify a unique owning object

  • inverseJoinColumns: Identifies the inverse (target) side of columns which are necessary to identify a unique target object

9.@JoinColumn

Maps a join column specified by the name identifier to the relationship table specified by @JoinTable


Example: CURD operations using Annotations

CREATE TABLE `studenttable` (
`sno` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NULL DEFAULT NULL,
`address` VARCHAR(50) NULL DEFAULT NULL,
PRIMARY KEY (`sno`)
)

StudentBo.java

package annotations;

@Entity
@Table(name="studenttable")
public class StudentBo {
	
@Id
@Column(name="sno")
@GeneratedValue(strategy=GenerationType.AUTO)
private int sno; //PRIMARY_KEY

@Column(name="name")
private String name;

@Column  //By default it will take datamember name
private String address;

@Transient
private String iamnotindatabase; 
//This column not their in db

public int getSno() {
	return sno;
}

public void setSno(int sno) {
	this.sno = sno;
}

public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}

public String getAddress() {
	return address;
}

public void setAddress(String address) {
	this.address = address;
}

public StudentBo( String name, String address) {
	super();
 
	this.name = name;
	this.address = address;
}
public StudentBo() {
	super();	 
}
}
<hibernate-configuration>
<session-factory>
 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/smlcodes</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.connection.password">root</property>

 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="show_sql">true</property>
 <property name="hbm2ddl.auto">update</property>

 <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
 <property name="hibernate.cache.use_second_level_cache">true</property>
 
 <mapping class="annotations.StudentBo"/> 
</session-factory>
</hibernate-configuration>

AnnotationExample.java

package annotations;
public class AnnotationExample {
public static void main(String[] args) {

 Configuration cfg = new AnnotationConfiguration();
 cfg.configure("hibernate.cfg.xml"); 

 SessionFactory sf = cfg.buildSessionFactory();
 Session session = sf.openSession();
 Transaction tx = session.beginTransaction(); 
 System.out.println("1.Save Operation");
 System.out.println("===============================");
 StudentBo e1 = new StudentBo("SATYA", "HYD");
 StudentBo e2 = new StudentBo("RAM", "BANGLORE");
 StudentBo e3 = new StudentBo("KIRAN", "MUMBAI");
 session.save(e1);
 session.save(e2);
 session.save(e3);
  
 System.out.println("2.Select Operation");
 System.out.println("===============================");
 List<StudentBo> ob = session.createQuery("FROM StudentBo").list();  
 for (StudentBo e : ob) {
 System.out.println(e.getSno()+", "+e.getName()+", "+e.getAddress());
 }
 tx.commit();
 session.close();
 sf.close();
 }
}
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
1.Save Operation
===============================
Hibernate: insert into studenttable (name, address) values (?, ?)
Hibernate: insert into studenttable (name, address) values (?, ?)
Hibernate: insert into studenttable (name, address) values (?, ?)
2.Select Operation
===============================
Hibernate: select studentbo0_.sno as sno0_, studentbo0_.name as name0_, studentbo0_.address as address0_ from studenttable studentbo0_
1, SATYA, HYD
2, RAM, BANGLORE
3, KIRAN, MUMBAI