Spring ORM Using Hibernate Template
Spring ORM Using Hibernate Template
Folder Structure:
config.xml:
<context:annotation-config/>
<context:component-scan base-package="com.app"/>
<bean class="com.app.Address" name="addr123,addr124">
</bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
name="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
name="sessionFactory">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.app.Employee</value>
</list>
</property>
</bean>
<bean class="org.springframework.orm.hibernate3.HibernateTemplate"
name="template">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</property>
</bean>
</beans>
Employee.java
package com.app;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="emp")
public class Employee {
@Id
@Column(name="eid")
private Integer empId;
@Column(name="ename")
private String empName;
@Column(name="esal")
private Double empSal;
public Employee() {
super();
}
}
package com.app;
import java.util.List;
package com.app;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
@Override
public Integer updateEmployee(Employee emp) {
template.update(emp);
return emp.getEmpId();
}
@Override
public Integer deleteEmployee(Integer empId) {
Employee emp=template.get(Employee.class, empId);
if (emp!=null) {
template.delete(emp);
}
return emp.getEmpId();
}
@Override
public Employee loadEmployee(Integer empId) {
@Override
public List<Employee> getAllEmployees() {
return template.loadAll(Employee.class);
}
}
Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.app.Employee;
import com.app.IEmployeeDao;
/**
* @param args
* @author Raghu
*/
public static void main(String[] args) {
ApplicationContext context=new
ClassPathXmlApplicationContext("config.xml");
IEmployeeDao empDao=(IEmployeeDao)context.getBean("empDao");
Employee emp=new Employee(103,"ka", 16.5);
System.out.println(empDao.getAllEmployees());
}
http://sourceforge.net/projects/hibernate/files/hibernate3/3.6.5.Final/hibernate-distribution-3.6.5.Final-
dist.zip/download