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
<mapping class="bean.Student">
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
Ex:
@Entity
@Table(name="StudentData")
|
3. @Id
Every table has a primary key, we can make the data member as Primary Key using @Id annotation.
Ex:
@Id
private int id;
4. @GeneratedValue
· It will generate the Primary Key/ ID values automatically
Ex:
@GeneratedValue(strategy=GenerationType.AUTO)
5. @Column
This Annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name by default.
Ex:
@Column(name="name")
private String name;
6. @Transient
· We can declare the data members which are not have columns in database table.
Example
StudentEntity.java
package bo;
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;
@Entity
@Table(name="StudentData")
public class StudentEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="name")
private String name;
@Column
private String address;
@Column
private String state;
@Transient
private String nothing;
public String getNothing() {
return nothing;
}
public void setNothing(String nothing) {
this.nothing = nothing;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
//Default Constrcutor
public StudentEntity() {
System.out.println("Auto-generated constructor");
}
//pamaerterized contsructor
public StudentEntity(String name, String address, String state){
this.name = name;
this.address = address;
this.state = state;
}
}
AnnotationExample.java
package dao;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import bo.StudentEntity;
public class AnnotationExample {
public static void main(String[] args) {
Configuration cfg = new AnnotationConfiguration();
cfg.configure("res/hibernate.cfg.xml");
System.out.println("===============================");
System.out.println("1. Table is created");
System.out.println("===============================");
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
System.out.println("===============================");
System.out.println("2. Save Operation");
System.out.println("===============================");
StudentEntity e1 = new StudentEntity("RAJESH", "HYD", "TS");
StudentEntity e2 = new StudentEntity("VINOD", "VJA", "AP");
StudentEntity e3 = new StudentEntity("SRIRAM", "BANG", "KARNATAKA");
session.save(e1);
session.save(e2);
session.save(e3);
System.out.println("===============================");
System.out.println("3. Select Operation");
System.out.println("===============================");
List<StudentEntity> ob = session.createQuery("FROM StudentEntity").list();
int i=1;
for(StudentEntity e: ob)
{
System.out.println(i+" | "+e.getId()+" | "+e.getName()+" | "+e.getAddress()+" | "+e.getState());
i++;
}
tx.commit();
session.close();
sf.close();
}
}
hibernate.cfg.xml
<?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">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">infy</property>
<property name="connection.pool_size">1</property>
<!-- Hibernate Properteies -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="bo.StudentEntity"/>
</session-factory>
</hibernate-configuration>
Output:
INFO: HHH000041: Configured SessionFactory: null
===============================
1. Table is created
===============================
Jul 31, 2015 1:20:12 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000397: Using ASTQueryTranslatorFactory
Auto-generated constructor
Jul 31, 2015 1:20:13 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: drop table if exists StudentData
Hibernate: create table StudentData (id integer not null auto_increment, address varchar(255), name varchar(255), state varchar(255), primary key (id))
Jul 31, 2015 1:20:13 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
===============================
2. Save Operation
===============================
Hibernate: insert into StudentData (address, name, state) values (?, ?, ?)
Hibernate: insert into StudentData (address, name, state) values (?, ?, ?)
Hibernate: insert into StudentData (address, name, state) values (?, ?, ?)
===============================
3. Select Operation
===============================
Hibernate: select studentent0_.id as id1_0_, studentent0_.address as address2_0_, studentent0_.name as name3_0_, studentent0_.state as state4_0_ from StudentDatastudentent0_
1 | 1 | RAJESH | HYD | TS
2 | 2 | VINOD | VJA | AP
3 | 3 | SRIRAM | BANG | KARNATAKA