spring整合Hibernate需要导入spring和hibernate必要的jar包,如果有相同的jar包,去掉旧的,保留新的和大的jar包。
需要的配置文件有spring的applicationContext.xml,hibernate的hibernate.cfg.xml,还有po类的Xxx.hbm.xml
下面以Emp类为例:
import java.util.Date;
/**
* Emp generated by MyEclipse Persistence Tools
*/
public class Emp implements java.io.Serializable {
private Integer empno;
private Dept dept;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Integer sal;
private Integer comm;
// Constructors
/** default constructor */
public Emp() {
}
public Emp(Integer empno, String ename, String job, Integer sal) {
super();
this.empno = empno;
this.ename = ename;
this.job = job;
this.sal = sal;
}
/** full constructor */
public Emp(Dept dept, String ename, String job, Integer mgr, Date hiredate, Integer sal, Integer comm) {
this.dept = dept;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
}
// Property accessors
public Integer getEmpno() {
return this.empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public Dept getDept() {
return this.dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public String getEname() {
return this.ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return this.job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getMgr() {
return this.mgr;
}
public void setMgr(Integer mgr) {
this.mgr = mgr;
}
public Date getHiredate() {
return this.hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public Integer getSal() {
return this.sal;
}
public void setSal(Integer sal) {
this.sal = sal;
}
public Integer getComm() {
return this.comm;
}
public void setComm(Integer comm) {
this.comm = comm;
}
}
下面是Emp.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 package="com.xxx.po">
<class name="Emp" table="emp" catalog="struts2">
<id name="empno" type="java.lang.Integer">
<column name="EMPNO" />
<generator class="native"></generator>
</id>
<many-to-one name="dept" class="Dept" fetch="select">
<column name="DEPTNO" />
</many-to-one>
<property name="ename" type="java.lang.String">
<column name="ENAME" length="10" />
</property>
<property name="job" type="java.lang.String">
<column name="JOB" length="9" />
</property>
<property name="mgr" type="java.lang.Integer">
<column name="MGR" />
</property>
<property name="hiredate" type="java.util.Date">
<column name="HIREDATE" length="10" />
</property>
<property name="sal" type="java.lang.Integer">
<column name="SAL" />
</property>
<property name="comm" type="java.lang.Integer">
<column name="COMM" />
</property>
</class>
</hibernate-mapping>
下面是hibernate的配置文件hibernate.cfg.xml内容:
<!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="myeclipse.connection.profile">test</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/struts2
</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<mapping resource="com/xxx/po/Dept.hbm.xml" />
<mapping resource="com/xxx/po/Emp.hbm.xml" />
</session-factory>
</hibernate-configuration>
下面是一个dao的实现类,里面简单的写了几个方法:spring也提供了一个工具类来操作数据,就是HibernateTemplate,要使用此类,需要注入一个SessionFactory
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class EmpDaoImpl implements IEmpDao {
private HibernateTemplate hibernateTemplate;
// 注入SessionFactory
public void setSessionFactory(SessionFactory sessionFactory){
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
// 根据empno删除emp数据
public void deleteById(int empno) {
Emp emp = new Emp();
emp.setEmpno(7934);
hibernateTemplate.delete(emp);
}
public long findCount() {
String hql = "select count(empno) from Emp";
return (Long) hibernateTemplate.find(hql).get(0);
}
// 根据id查询对象
public Emp findEmpById(int empno) {
return (Emp) hibernateTemplate.get(Emp.class, empno);
}
public List<Emp> findEmps() {
// 要求只查询出5个属性的,使用hql的构造方法查询
String hql = "select new com.xxx.po.Emp(empno,ename,job,sal) from Emp ";
return hibernateTemplate.find(hql);
}
public List<Emp> findPage(final int firstResult, final int maxResult) {
// hibernate 对分页的支持很好,只能使用回调调用session
return (List<Emp>) hibernateTemplate.execute(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException, SQLException {
String hql = "from Emp";
return session.createQuery(hql)
.setFirstResult(firstResult)
.setMaxResults(maxResult)
.list();
}
});
}
}
最后是配置spring配置文件applicationContext.xml,这种方式是直接读取了hibernate.cfg.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context definition for JPetStore's business layer.
- Contains bean references to the transaction manager and to the DAOs in
- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 配置SessionFactory :1)读取hibernate.cfg.xml文件-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 1 指定事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 2 配置事务的特性(事务的传播特性和事务的隔离级别) -->
<tx:advice id="mAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="NOT_SUPPORTED" isolation="READ_COMMITTED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
</tx:attributes>
</tx:advice>
<!-- 3 配置Aop:事务配置service层(此处没有service就配置到了dao层) -->
<aop:config>
<aop:pointcut id="curd" expression="execution (* com.xxx.dao..*.*(..))"/>
<aop:advisor advice-ref="mAdvice" pointcut-ref="curd"/>
</aop:config>
<bean id="empDao" class="com.xxx.dao.impl.EmpDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
我们也可以丢弃掉hibernate.cfg.xml文件,把这些信息配置到.properties文件中,然后在spring配置文件中读取,这样的好处是,项目完结后,源代码一般不给,就可以给这个.properties配置文件,用户可以根据需要自行修改里面的内容
hibernate用的c3p0连接池,所以我这里就把配置文件名称叫做c3p0.properties,内容为:
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/struts2
jdbc.username=root
jdbc.password=1234
dialect=org.hibernate.dialect.MySQLDialect
ShowSql=true
spring配置文件就这样配置:
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context definition for JPetStore's business layer.
- Contains bean references to the transaction manager and to the DAOs in
- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 读取C3P0.properties文件 -->
<context:property-placeholder location="classpath:c3p0.properties"/>
<!-- 配置SessionFactory :
3参数:
连接池 hibernate自身特性 注册映射文件
连接池(C3p0)可以在外界修改参数
C3P0核心类:ComboPooledDataSource
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${dialect}</prop>
<prop key="hibernate.show_sql">${ShowSql}</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/xxx/po/Dept.hbm.xml</value>
<value>com/xxx/po/Emp.hbm.xml</value>
</list>
</property>
</bean>
<!-- 1 指定事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 2 配置事务的特性(事务的传播特性和事务的隔离级别) -->
<tx:advice id="mAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*"
propagation="NOT_SUPPORTED"
isolation="READ_COMMITTED"
read-only="true"
/>
<tx:method name="*"
propagation="REQUIRED"
isolation="READ_COMMITTED"
/>
</tx:attributes>
</tx:advice>
<!-- 3 配置Aop:事务配置service层 -->
<aop:config>
<aop:pointcut id="curd" expression="execution (* com.xxx.dao..*.*(..))"/>
<aop:advisor advice-ref="mAdvice" pointcut-ref="curd"/>
</aop:config>
<bean id="empDao" class="com.xxx.dao.impl.EmpDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
自此,spring整合hibernate就算配置完成了。