Hibernate Annotations and Spring
Let us make the previous Hibernate Application to Spring application with the same entity class Item.java and Sale.java
Step 1:
Let us make DAO classes MyDAO.java and MyDAOImpl.java
//MyDAO.java
package me.gs.dao;
import me.gs.model.Item;
import me.gs.model.Sale;
public interface MyDAO {
public void saveItem(Item item);
public void saveSale(Sale sale);
}
//MyDAOImpl.java
package me.gs.dao;
import me.gs.model.Item;
import me.gs.model.Sale;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
@Repository("MyDAO")
public class MyDAOImpl implements MyDAO
{
private HibernateTemplate hibernateTemplate;
@Autowired
public void createHibernateTemplate(SessionFactory sessionFactory)
{
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public void saveItem(Item item)
{
hibernateTemplate.save(item);
}
public void saveSale(Sale sale)
{
hibernateTemplate.save(sale);
}
}
Step 2:
Add jdbc.properties file inside the WEB-INF directory with bellow code
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/my jdbc.username=root jdbc.password=
Step 3:
we may remove bellow code from hibernate.cfg.xml or comment or let it be exist in fact its not needed as we added jdbc.properties file
< 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>
Step 4:
Locate the applicationContext.xml and edit with the bellow code inside the WEB-INF folder
Step 5: Let us make a jUnit test class to test the application this time.
import me.gs.dao.MyDAO;
import me.gs.model.Item;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestSpring
{
public TestSpring()
{
}
@Test
public void testSpringHB()
{
ApplicationContext context = new FileSystemXmlApplicationContext("web/WEB-INF/applicationContext.xml");
MyDAO idao = (MyDAO) context.getBean("MyDAO");
Item item = new Item();
item.setName("item3");
item.setCode("code3");
idao.saveItem(item);
}
}
Output comes as bellow:
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.
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:
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 + "]";
}
}
@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