Spring 集成Hibernate
我们可以简单地将hibernate应用程序与spring应用程序集成。
在hibernate框架中,我们提供了所有功能数据库信息hibernate.cfg.xml文件。
但是,如果我们要将hibernate应用程序与spring集成在一起,则无需创建hibernate.cfg.xml文件。我们可以在applicationContext.xml文件中提供所有信息。
Spring框架具有休眠功能的优势
Spring框架提供了
HibernateTemplate 类,因此您无需执行太多步骤,例如创建Configuration,BuildSessionFactory,Session,开始和提交事务等。
因此
它节省了大量代码。
不使用spring的理解问题:
下面的休眠代码让我们理解它:
//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
//creating session object
Session session=factory.openSession();
//creating transaction object
Transaction t=session.beginTransaction();
Employee e1=new Employee(111,"arun",40000);
session.persist(e1);//persisting the object
t.commit();//transaction is commited
session.close();
正如您在唯一的hibernate代码中所看到的,您必须遵循许多步骤。
使用Spring Framework的HibernateTemplate类的解决方案:
现在,您无需执行太多步骤。您可以简单地这样写:
Employee e1=new Employee(111,"arun",40000);
hibernateTemplate.save(e1);
HibernateTemplate类的方法
我们来看看HibernateTemplate类的常用方法列表。
方法 |
说明 |
void persist(Object entity) |
坚持给定的对象。 |
Serializable save(Object entity) |
保留给定对象并返回ID。 |
void saveOrUpdate(Object entity) |
持久或更新给定的对象。如果找到id,它将更新记录,否则保存记录。 |
void update(Object entity) |
更新给定的对象。 |
void delete(Object entity) |
根据id删除给定的对象。 |
Object get(Class entityClass, Serializable id) |
根据给定的id返回持久对象。 |
Object load(Class entityClass, Serializable id) |
根据给定的id返回持久对象。 |
List loadAll(Class entityClass) |
返回所有持久对象。 |
步骤
让我们看看休眠和弹簧集成的简单步骤是什么:
在数据库中创建表。这是可选的。
创建applicationContext.xml文件。其中包含DataSource,SessionFactory等的信息。
创建Employee.java文件。这是持久性类
创建employee.hbm.xml文件。它是映射文件。
创建EmployeeDao.java文件。它是使用HibernateTemplate的dao类。
创建InsertTest.java文件。它将调用EmployeeDao类的方法。
Hibernate和spring集成的示例
在此示例中,我们将把hibernate应用程序与spring集成。让我们看看spring和hibernate示例的
目录结构。
1、在数据库中创建表
在此示例中,我们使用Oracle作为数据库,但是您可以使用任何数据库。让我们在oracle数据库中创建表
CREATE TABLE "EMP558"
( "ID" NUMBER(10,0) NOT null ENABLE,
"NAME" VARCHAR2(255 CHAR),
"SALARY" float(126),
PRIMARY KEY ("ID") ENABLE
)
/
2、Employee.java
这是一个简单的POJO类。在这里,它用作休眠的持久类。
package com.lidihuo;
public class Employee {
private int id;
private String name;
private float salary;
//getters and setters
}
3、employee.hbm.xml
此映射文件包含持久类的所有信息。
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.lidihuo.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
4、EmployeeDao.java
这是一个使用
HibernateTemplate 类方法来持久保存Employee类对象的Java类。
package com.lidihuo;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
//method to save employee
public void saveEmployee(Employee e){
template.save(e);
}
//method to update employee
public void updateEmployee(Employee e){
template.update(e);
}
//method to delete employee
public void deleteEmployee(Employee e){
template.delete(e);
}
//method to return one employee of given id
public Employee getById(int id){
Employee e=(Employee)template.get(Employee.class,id);
return e;
}
//method to return all employees
public List<Employee> getEmployees(){
List<Employee> list=new ArrayList<Employee>();
list=template.loadAll(Employee.class);
return list;
}
}
5、applicationContext.xml
在此文件中,我们在
BasicDataSource 对象中提供数据库的所有信息。该对象用于
LocalSessionFactoryBean 类对象,其中包含一些其他信息,例如mappingResources和hibernateProperties。
LocalSessionFactoryBean 类的对象在HibernateTemplate类中使用。让我们看一下applicationContext.xml文件的代码。
文件: applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="oracle"></property>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="com.lidihuo.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>
6、InsertTest.java
此类使用EmployeeDao类对象,并通过传递Employee类的对象来调用其saveEmployee方法。
package com.lidihuo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class InsertTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
EmployeeDao dao=(EmployeeDao)factory.getBean("d");
Employee e=new Employee();
e.setId(114);
e.setName("varun");
e.setSalary(50000);
dao.saveEmployee(e);
}
}
现在,如果您在oracle数据库中看到该表,则记录已成功插入。
启用自动表创建,显示sql查询等。
您可以在applicationContext.xml文件中启用hibernate属性,例如通过hbm2ddl.auto等进行自动表创建。让我们看一下代码:
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
如果编写此代码,则无需创建表,因为将自动创建表。