下面介绍一下hibernate与spring的集成,这两个框架的集成关键在于applicationContext.xml文件的配置,其实很简单的,但需要注意的是,导入包时一定选择导入到webroot/web-inf/lib目录中,而且hibernate一般要在spring之前导入,因为集成时要用到sessionFactory类,
一、初始化工作:新建一个项目,如(ssh),在此项目中导入对hibernate的支持,新建一个表sstest表,有字段id,username,password,id为主健和自动增1
二、对新建的数据表进行hibernate进行映射,打开myhibernate视图,右击你sstest表->选hibernate revers engineering选项,然后把Sstest.hbm.xml文件映射到hibernateDao包中,同时选中工具 hibernate mapping file..., java data object....., java data access object dao...选项,先中这几个文件就可以产生下列几个.java文件:BaseHibernateDAO. ,HibernateSessionFactory ,IBaseHibernateDAO, Sstest,SstestDAO,最后你对你的代码进行测试,测试成功,进行下一步
三、在项目中导入对spring的支持,在导入项目后不但要自动产生applicationContext.xml,而且在这个文件里会出现下面的内容:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml">
</property>
</bean>
这就是为什么要先要导入hibernate的原因
四、若你对spring的ioc比较熟,你可以直接进入下一步,如果不是很了解,那么你可以写一个比较简单的例子测试一下看是否成功,必竟框架和在一起,所以小心点好,不然在以后出了有问题不好找
五、进入myeclipse hibernate视图下,在新的包(如springDao)中重新对sstest表进行映射,这次映射要注意的就是:打开hibernate reverse engineering对话框中复选按钮java data access object(dao)(hibernate 3 only)下,dao type 不是选basic dao选项,而是选spring dao选项,当你映射成功后,就会出现Sstest.java, SstestDAO.java, Sstest.hbm.xml几个文件,你可以写一个类进行测试,如:
springdaotest.java
package org.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import springDao.Sstest;
import springDao.SstestDAO;
public class SpringDaoTest {
public static void main(String a[]){
ApplicationContext cont = new ClassPathXmlApplicationContext("applicationContext.xml");
SstestDAO s = (SstestDAO) cont.getBean("SstestDAO");
SstestDAO s = (SstestDAO) cont.getBean("SstestDAOProxy");
Sstest st = new Sstest();
st.setUsername("spring");
st.setPassword("spring");
s.save(st);
}
}
六、由于映射了两次,所以你要在hibernate.cfg.xml文件中,把原来映射的文件注解掉:
<mapping resource="hibernateDao/Sstest.hbm.xml" />
因为现在已有一行这样的代码:
<mapping resource="springDao/Sstest.hbm.xml" />
七、实现hibernate spring 代理,加上下面的代码即可:
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="SstestDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="proxyTargetClass">
<value>true</value>
</property>
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="target">
<ref local="SstestDAO"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
在进行测试,测试时,还是用原来的类,只需把SstestDAO s = (SstestDAO) cont.getBean("SstestDAO");变成
SstestDAO s = (SstestDAO) cont.getBean("SstestDAOProxy");这次的bean是用的代码类实现
下面是完整的代码:
在这个实例中hibernate包中的文件BaseHibernateDAO. ,HibernateSessionFactory ,IBaseHibernateDAO, Sstest,SstestDAO, Sstest.hbm.xml ,和在一个简单的struts,hibernate例子以及struts,hibernate集成中的文件是一样的,代码一样,下面是一些其它代码:
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml">
</property>
</bean>
<!-- spring dao -->
<bean id="SstestDAO" class="springDao.SstestDAO">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- hibernate 3 事务代理 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="SstestDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="proxyTargetClass">
<value>true</value>
</property>
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="target">
<ref local="SstestDAO"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
</beans>
测试类:SpringDaoTest.java
package org.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import springDao.Sstest;
import springDao.SstestDAO;
public class SpringDaoTest {
public static void main(String a[]){
ApplicationContext cont = new ClassPathXmlApplicationContext("applicationContext.xml");
//SstestDAO s = (SstestDAO) cont.getBean("SstestDAO");
//代理类
SstestDAO s = (SstestDAO) cont.getBean("SstestDAOProxy");
Sstest st = new Sstest();
st.setUsername("spring");
st.setPassword("spring");
s.save(st);
}
}
Sstest.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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="springDao.Sstest" table="sstest" schema="dbo" catalog="manager">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="increment" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="10" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="20" />
</property>
</class>
</hibernate-mapping>
SstestDAO.java
package springDao;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class SstestDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(SstestDAO.class);
// property constants
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
protected void initDao() {
// do nothing
}
public void save(Sstest transientInstance) {
log.debug("saving Sstest instance");
System.out.println("Ok");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
System.out.print("save Ok");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Sstest persistentInstance) {
log.debug("deleting Sstest instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Sstest findById(java.lang.Integer id) {
log.debug("getting Sstest instance with id: " + id);
try {
Sstest instance = (Sstest) getHibernateTemplate().get(
"springDao.Sstest", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Sstest instance) {
log.debug("finding Sstest instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Sstest instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Sstest as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByUsername(Object username) {
return findByProperty(USERNAME, username);
}
public List findByPassword(Object password) {
return findByProperty(PASSWORD, password);
}
public List findAll() {
log.debug("finding all Sstest instances");
try {
String queryString = "from Sstest";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Sstest merge(Sstest detachedInstance) {
log.debug("merging Sstest instance");
try {
Sstest result = (Sstest) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Sstest instance) {
log.debug("attaching dirty Sstest instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Sstest instance) {
log.debug("attaching clean Sstest instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static SstestDAO getFromApplicationContext(ApplicationContext ctx) {
return (SstestDAO) ctx.getBean("SstestDAO");
}
}
Sstest.java
package springDao;
public class Sstest implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private String password;
// Constructors
/** default constructor */
public Sstest() {
}
/** full constructor */
public Sstest(String username, String password) {
this.username = username;
this.password = password;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
hibernate.cfg.xml
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">sa</property>
<property name="connection.url">
jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=manager
</property>
<property name="dialect">
org.hibernate.dialect.SQLServerDialect
</property>
<property name="myeclipse.connection.profile">
com.microsoft.jdbc.sqlserver.SQLServerDriver
</property>
<property name="connection.password">wq</property>
<property name="connection.driver_class">
com.microsoft.jdbc.sqlserver.SQLServerDriver
</property>
<!-- <mapping resource="hibernateDao/Sstest.hbm.xml" /> -->
<!-- 使用springdao -->
<mapping resource="springDao/Sstest.hbm.xml" />
</session-factory>
</hibernate-configuration>