Hibernate Annotations and Relationships
Hibernate Annotation brings up a concept of transferring data from POJO (Plain Old Java Object) to database tables in the form of Metadata. which replaces earlier hibernate versions which uses XML files to work with metadata.
Java 5 on words metadata can be handled by JVM itself, this technique is called as Annotation. Annotation is the Java class which is read through reflection mechanism during the runtime by JVM and does the processing accordingly. Here Hibernate Annotation is to providing raw metadata for mapping Object and Relational Tables. All metadata comes with an Entity class containing table structure so that programmer simultaneously can hook up with required structure and relationships without having lengthy XML mapping files.
The current Hibernate Annotation release is based on the EJB 3 and JPA specification.
Let us see an example of this topic:
What needed before you proceed?
What needed before you proceed?
- Java 5.0 or Higher installed in your system.
- Download Hibernate Core 3.3.1.GA then extract and set all jar files to your classpath.
- Download Hibernate Annotations 3.4.0 GA.
- You should also have hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and lib/ejb3-persistence.jar from the Hibernate Annotations distribution to your classpath.
- Better if you know hibernate already.
Preface of Application:
We will make an application which shows the Item and its Sale relationships. So here tables are item and sale, there will be another table for Item and Sale relationship sale_item. All these three tables will be generated by Hibernate Annotation core automatically without our intricacy.
Database Name :my
User Name : root
Password :
Database Name :my
User Name : root
Password :
Step 1: Create an Entity Class Item.java this is the POJO class for Items
package me.gs.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
fields are not set
if (!(object instanceof Item)) {
return false;
}
Item other = (Item) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "me.gs.model.Item[id=" + id + "]";
}
}
Here @Entity declares the class as an entity bean i.e. a persistent POJO class and @Id declares the identifier property of this entity bean which is also Primary Key of the tables. @Column is used to map the entities with the column in the database.We can also define the table name as bellow
@Entity@Table(name="item")
public class Item implements Serializable {
...
Step 2 : Create another entity class Sale.java which is same as Item.java class
package me.gs.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Sale implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String refNo;
@OneToMany
private List
public List
return items;
}
public void setItems(List
this.items = items;
}
public String getRefNo() {
return refNo;
}
public void setRefNo(String refNo) {
this.refNo = refNo;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
fields are not set
if (!(object instanceof Sale)) {
return false;
}
Sale other = (Sale) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "me.gs.model.Sale[id=" + id + "]";
}
}
Bellow two statements make the OneToMany relationship between Item and Sale class.
@OneToMany
private List
Step 3: The Hibernate.cfg.xml is the configuration file for the datasource in the Hibernate. Our file will look something like this.
<?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.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/my</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping class="me.gs.model.Item"></mapping>
<mapping class="me.gs.model.Sale"></mapping>
</session-factory>
</hibernate-configuration>
Step 4: This following program we can use to test the entire application we have designed so far.
import java.util.ArrayList;
import java.util.List;
import me.gs.model.Item;
import me.gs.model.Sale;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public class HiberTestMain {
public static void main(String args[])
{
System.out.println("start");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Item item = new Item();
item.setName("item1");
item.setCode("code1");
Item item1 = new Item();
item1.setName("item2");
item1.setCode("code2");
session.save(item);
session.save(item1);
Sale sale = new Sale();
sale.setRefNo("refNo1");
List
items.add(item);
items.add(item1);
sale.setItems(items);
session.save(sale);
transaction.commit();
session.close();
System.out.println("end");
}
}
Output:
start
Hibernate: insert into Item (code, name) values (?, ?)
Hibernate: insert into Item (code, name) values (?, ?)
Hibernate: insert into Sale (refNo) values (?)
Hibernate: insert into Sale_Item (Sale_id, items_id) values (?, ?)
Hibernate: insert into Sale_Item (Sale_id, items_id) values (?, ?)
end
Finally in our MySQL database we will find three tables created with given data,
item
sale
sale_item
here sale_item defines the OneToMany relationship of item and sale.
Thanks.
Special Thanks to Mehrab Ferdous
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment