核心思想主要是spring来管理hibernate 在spring配置中配置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" 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"> <!-- 数据源配置 jndi : org.springframework.jndi.JndiObjectFactoryBean jdbc : org.springframework.jdbc.datasource.DriverManagerDataSource dbcp连接池:org.apache.commons.dbcp.BasicDataSource --> <!-- <bean id="dataSourceJndi" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/magus" /> </bean> --> <bean id="dataSourceJdbc" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ssh"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="dataSourceDbcp" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/ssh"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1" /> <!-- 连接池的最大值 --> <property name="maxActive" value="500" /> <!-- 最大空闲值 当经过一段高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="10" /> <!-- 最小空闲值 当空闲的连接数小于阀值时,连接池就会去预申请一些连接,以免洪峰时来不及申请 --> <property name="minIdle" value="5" /> </bean> <!-- 定义一个hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 注入DataSource --> <property name="dataSource" ref="dataSourceJdbc" /> <!-- 配置hibernate的相关属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> <!-- com.magus.sqlserver2008.SQLServer2008Dialect --> <!-- org.hibernate.dialect.Oracle9Dialect --> <!-- org.hibernate.dialect.OracleDialect --> <!-- org.hibernate.dialect.MySQLDialect --> org.hibernate.dialect.MySQLDialect </prop> </props> </property> <property name="configLocation" value="classpath:hibernate.cfg.xml"> </property> </bean> <!-- 定义事务管理器,使用适用于Hibernte的事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <!-- HibernateTransactionManager 需要依赖注入一个SessionFactory bean的引用 --> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 定义DAO Bean , 作为事务代理的目标 --> <bean id="personServiceBean" class="com.ch.dao.impl.PersonServiceBean"> <!-- 为DAO bean注入SessionFactory引用 --> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 给具体操作数据库的service配置事务。定义DAO bean的事务代理 (xml声明式)--> <!-- getHibernateTemplate().getSessionFactory().getCurrentSession()是得到当前线程绑定的session, 而当前线程绑定的session是通过当前的事务产生的。 如果你没有配置事务的话,当前线程threadlocal中就不存在 session, 这样就出现No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here错误。 --> <bean id="personService1" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <!-- 为事务代理bean注入事务管理器 --> <property name="transactionManager" ref="transactionManager"> </property> <!-- 设置事务属性 --> <property name="transactionAttributes"> <props> <!-- 所有以find开头的方法,采用required的事务策略,并且只读--> <prop key="find*">PROPAGATION_REQUIRED,readOnly </prop> <prop key="get*">PROPAGATION_REQUIRED,readOnly </prop> <prop key="is*">PROPAGATION_REQUIRED,readOnly </prop> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="batchDelete*">PROPAGATION_REQUIRED</prop> <prop key="new*">PROPAGATION_REQUIRED</prop> </props> </property> <!-- 设置事务代理的目标bean --> <property name="target"> <ref local="personServiceBean" /> <!-- 采用嵌套bean配置目标bean (避免目标bean被误引用)--> <!-- <bean class="com.ch.dao.impl.PersonServiceBean"> <property name="sessionFactory" ref="sessionFactory" /> </bean> --> </property> </bean> <!-- 大部分情况下,每个事务代理的事务属性大同小异,事务代理的实现类都是TransactionProxyFactoryBean, 事务代理bean都必须注入事务管理器。 所以Spring提供了bean与bean之间的继承,将大部分的通用配置,配置成事务模板,而实际的事务代理bean,则继承事务模板。 这种配置方式可以减少部分配置代码,下面是采用继承的配置文件: --> <bean id="tranProxyTemplate" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true"> <!-- 为事务代理bean注入事务管理器 --> <property name="transactionManager" ref="transactionManager"> </property> <!-- 设置事务属性 --> <property name="transactionAttributes"> <props> <!-- 所有以find开头的方法,采用required的事务策略,并且只读--> <prop key="find*">PROPAGATION_REQUIRED,readOnly </prop> <prop key="get*">PROPAGATION_REQUIRED,readOnly </prop> <prop key="is*">PROPAGATION_REQUIRED,readOnly </prop> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="batchDelete*">PROPAGATION_REQUIRED</prop> <prop key="new*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <bean id="personService" parent="tranProxyTemplate" > <!-- 设置事务代理的目标bean --> <property name="target"> <ref local="personServiceBean" /> <!-- 采用嵌套bean配置目标bean (避免目标bean被误引用)--> <!-- <bean class="com.ch.dao.impl.PersonServiceBean"> <property name="sessionFactory" ref="sessionFactory" /> </bean> --> </property> </bean> </beans>
service层接口
package com.ch.dao; import com.ch.entity.Person; public interface IPersonService { public void save(Person person) ; public void update(Person person); public Person find(Integer personId); public void delete(Person person); }
service层实现
package com.ch.dao.impl; import java.util.List; import org.hibernate.SessionFactory; import com.ch.dao.IPersonService; import com.ch.entity.Person; public class PersonServiceBean implements IPersonService { private SessionFactory sessionFactory; public void delete(Person person) { sessionFactory.getCurrentSession().delete(person); } public Person find(Integer personId) { Person person = (Person) sessionFactory.getCurrentSession().get( Person.class, personId); return person; } public void save(Person person) { sessionFactory.getCurrentSession().save(person); } public void update(Person person) { sessionFactory.getCurrentSession().merge(person); } public List<?> findAllPersons() { return sessionFactory.getCurrentSession().createQuery("from Person").list(); } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
hibernate配置文件
<?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> <!-- 数据库链接配置,在此处未使用 使用的是spring的数据库配置 --> <property name="myeclipse.connection.profile">mysqlssh</property> <property name="connection.url"> jdbc:mysql://localhost:3306/ssh </property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <!-- 指定额外的Hibernate属性 --> <property name="show_sql">true</property> <!-- 指定Hibernate映射资源的位置 --> <mapping resource="com/ch/entity/Person.hbm.xml" /> </session-factory> </hibernate-configuration>
测试类
package com.ch.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ch.dao.IPersonService; import com.ch.entity.Person; public class PersonTest { private IPersonService personService; public PersonTest() { ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContext.xml"); personService = (IPersonService) ac.getBean("personService"); } public void testSave() { Person p = new Person("小王"); personService.save(p); System.out.println("保存成功。。。。。"); } public void testUpdate() { Person p = personService.find(2); p.setPersonName("小张"); personService.update(p); System.out.println("更新成功。。。。。"); } public String testFind() { Person p = personService.find(1); System.out.println("查找成功。。。。。"); return p.getPersonName(); } public void testDelete() { Person p = personService.find(2); personService.delete(p); System.out.println("删除成功。。。。。"); } public static void main(String[] args) { PersonTest test = new PersonTest(); test.testSave(); // test.testUpdate(); // test.testFind(); // test.testDelete(); } }