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:


0 comments:

Post a Comment