需要的jar包
1、Spring核心必须依赖的库:commons-logging-1.1.1.jar
2、Spring IoC部分核心库:
- spring-beans-4.3.9.RELEASE.jar
- spring-context-4.3.9.RELEASE.jar
- spring-context-support-4.3.9.RELEASE.jar
- spring-core-4.3.9.RELEASE.jar
- spring-expression-4.3.9.RELEASE.jar
- spring-web-4.3.9.RELEASE.jar ------> 支持在Web环境中使用Spring IoC容器
3、Spring AOP部分核心库:
- spring-aop-4.3.9.RELEASE.jar
- spring-aspects-4.3.9.RELEASE.jar
4、Spring AOP需要依赖于aspectj库:
- aspectjrt.jar
- aspectjweaver.jar
5、Spring JDBC部分核心库:
- spring-jdbc-4.3.9.RELEASE.jar
- spring-tx-4.3.9.RELEASE.jar
6、Spring ORM部分核心库:
- spring-orm-4.3.9.RELEASE.jar
7、若配置的是c3p0数据源还需要:
- c3p0-0.9.5.2.jar
- hibernate-c3p0-5.2.10.Final.jar
- mchange-commons-java-0.2.11.jar
8、Hibernate部分核心库:
- antlr-2.7.7.jar
- classmate-1.3.0.jar
- dom4j-1.6.1.jar
- hibernate-commons-annotations-5.0.1.Final.jar
- hibernate-core-5.2.10.Final.jar
- hibernate-jpa-2.1-api-1.0.0.Final.jar
- jandex-2.0.3.Final.jar
- javassist-3.20.0-GA.jar
- jboss-logging-3.3.0.Final.jar
- jboss-transaction-api_1.2_spec-1.0.1.Final.jar
9、Ehcache部分核心库:
- ehcache-2.10.3.jar
- hibernate-ehcache-5.2.10.Final.jar
- slf4j-api-1.7.7.jar
10、数据库对应的驱动包:mysql-connector-java-5.1.40-bin.jar
Spring整合Hibernate
1、使用Spring依赖注入和AOP简化Hibernate应用,由IOC 容器来管理 Hibernate 的 SessionFactory,让 Hibernate 使用上 Spring 的声明式事务
2、整合步骤
- 引用jar包
- 创建数据库和表
DROP TABLE IF EXISTS t_customer ; CREATE TABLE t_customer ( id INT(5) PRIMARY KEY , email VARCHAR(60) UNIQUE NOT NULL, password VARCHAR(32) NOT NULL , nickname VARCHAR(150) , gender VARCHAR(3) , birthdate DATE , married CHAR(1) );
- 创建类创建类
Customer类
package ecut.hibernate.entity; import java.util.Date; public class Customer { private Integer id; private String email; private String password; private String nickname; private char gender; private Date birthdate; private boolean married; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public Date getBirthdate() { return birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } public boolean isMarried() { return married; } public void setMarried(boolean married) { this.married = married; } }
CustomerController类
package ecut.hibernate.controller; import java.util.List; import ecut.hibernate.entity.Customer; import ecut.hibernate.service.CustomerService; public class CustomerController { private CustomerService customerService ; public String regist( Customer c ){ System.out.println( "CustomerController # regist ." ); customerService.save( c ); return "success" ; } public List<Customer> allCustomer(){ return customerService.findAll(); } public CustomerService getCustomerService() { return customerService; } public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } }
CustomerService类
package ecut.hibernate.service; import java.util.List; import ecut.hibernate.dao.CustomerDao; import ecut.hibernate.entity.Customer; public class CustomerService { private CustomerDao customerDao ; public boolean save( Customer c ) { System.out.println( "CustomerService # save ." ); return customerDao.persist( c ); } public List<Customer> findAll(){ return customerDao.loadAll() ; } public CustomerDao getCustomerDao() { return customerDao; } public void setCustomerDao(CustomerDao customerDao) { this.customerDao = customerDao; } }
Spring配置文件
<?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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" > <!-- 注入数据源,用来获得数据库连接 --> <property name="dataSource" ref="dataSource" /> <!-- 注入 hibernate 的配置 ( 方言、二级缓存 、查询缓存) --> <property name="hibernateProperties"> <props> <!-- 指示数据库的基本信息 --> <!-- <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop> <prop key="hibernate.connection.url" >jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8</prop> <prop key="hibernate.connection.username" >root</prop> <prop key="hibernate.connection.password" >123456</prop> --> <!-- 启用二级缓存 --> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <!-- 启用查询缓存 --> <prop key="hibernate.cache.use_query_cache" >true</prop> <!-- 指定数据方言 类--> <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop> <!-- 指示是否显示sql --> <prop key="hibernate.show_sql" >true</prop> <!-- 指示是否对sql格式化输出 --> <prop key="hibernate.format_sql" >true</prop> </props> </property> <!-- 引入映射文件 --> <!-- mappingResources 对应的是 String 数组,不支持 使用 通配符 ,下面的写法是错误的 --> <!-- <property name="mappingResources" value="classpath:ecut/hibernate/entity/*.hbm.xml" /> --> <!-- mappingLocations 对应的 是 Resource 数组 ,因此 支持 使用 通配符 --> <property name="mappingLocations" value="classpath:ecut/hibernate/entity/*.hbm.xml"></property> </bean> <!-- 配置平台事务管理器 ,由HibernateTransactionManager类来完成事务管理--> <bean id="platformTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 提供对事务的配置 ( Advice ) --> <tx:advice id="transactionAdvice" transaction-manager="platformTransactionManager"> <tx:attributes> <tx:method name="persist*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" /> <tx:method name="save*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" /> <tx:method name="update*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" /> <tx:method name="delete*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" /> <tx:method name="remove*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" /> <tx:method name="load*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true" /> <tx:method name="get*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true" /> <tx:method name="query*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true" /> </tx:attributes> </tx:advice> <!-- aop实现事务控制:使用 aop:config 实现将 Advice 织入到 相应的 连接点中 --> <aop:config> <aop:pointcut id="tx-pointcut" expression="execution(* ecut.hibernate.service.*.*(..))"/> <!-- 声明事务控制 切面 --> <aop:advisor pointcut-ref="tx-pointcut" advice-ref="transactionAdvice"/> </aop:config> <!-- hibernate所有操作都是通过sessionFactory实现的 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="customerDao" class="ecut.hibernate.dao.CustomerDao" > <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean> <bean id="customerService" class="ecut.hibernate.service.CustomerService" > <property name="customerDao" ref="customerDao" /> </bean> <bean id="customerController" class="ecut.hibernate.controller.CustomerController" > <property name="customerService" ref="customerService" /> </bean> </beans>
在spring配置文件中,配置平台事务管理器 ,由HibernateTransactionManager类来完成事务管理,并引用sessionFactory。在sessionFactory中注入 hibernate 的配置 ( 方言、二级缓存 、查询缓存)和数据源,以及引入映射文件,需要注意的是引入配置文件时mappingLocations 对应的 是 Resource 数组 ,因此 支持 使用 通配符,但是mappingResources 对应的是 String 数组,不支持使用通配符。最终通过AOP来实现事务的控制。controller中添加了CustomerService的对象,因此需要将CustomerService以ref的方式引入到controller中。service中添加了CustomerDao的对象,因此需要将CustomerDao以ref的方式引入到service中。dao中添加了jdbcTemplate的对象,因此需要将jdbcTemplate以ref的方式引入到dao中。而Template依赖与DataSource,以ref的方式为JdbcTemplate注入引用。DataSource的属性可以通过注入数据库的一些配置属性添加。
Hibernate配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- 指定 那个类 ( name 指定类名 ) 对应 那个表 ( table 指定表名 ) --> <class name="ecut.hibernate.entity.Customer" table="t_customer"> <!-- 对于 与 数据库主键 对应的 对象标识符属性 来说,要单独使用 id 标签来映射 --> <id name="id" type="integer" column="id" > <generator class="increment" /> <!-- 由 hibernate 提供的 对象标识符 生成策略 --> </id> <!-- 指定 那个属性 ( name 指定属性名 ) 对应 那个列 ( column 属性指定 列名 ) --> <property name="email" type="string" column="email" /> <!-- 使用 type 属性指定 映射类型 ( 既不是 Java 类型,也不是 数据库类型,而是 中间类型 ( 媒婆 ) ) --> <property name="password" type="string" column="password" /> <property name="nickname" type="string" column="nickname" /> <!-- Java 中的 char 类型在 hibernate 中对应的映射类型是 character --> <property name="gender" type="character" column="gender" /> <property name="birthdate" type="date" column="birthdate" /> <!-- Java 中的 boolean 类型在 hibernate 中对应的映射类型可以是 true_false 、yes_no --> <property name="married" type="yes_no" column="married" /> </class> </hibernate-mapping>
CustomerDao类
package ecut.hibernate.dao; import java.io.Serializable; import java.util.List; import ecut.hibernate.entity.Customer; import org.springframework.orm.hibernate5.HibernateTemplate; public class CustomerDao { private HibernateTemplate hibernateTemplate; public boolean persist( Customer c ) { try{ //没有提交事务所以需要增加事务的配置 Serializable id = hibernateTemplate.save( c ); return id != null ; } catch ( Exception e) { e.printStackTrace(); return false ; } } public boolean update( Customer c ) { try{ hibernateTemplate.update( c ); return true ; } catch ( Exception e) { return false ; } } public boolean delete( Customer c ) { try{ hibernateTemplate.delete( c ); return true ; } catch ( Exception e) { return false ; } } public Customer load( Integer id ) { return hibernateTemplate.get( Customer.class , id ) ; } //@SuppressWarnings抑制编译器警告 @SuppressWarnings("unchecked") public List<Customer> loadAll() { final String HQL = "FROM Customer"; List<Customer> list = (List<Customer>)hibernateTemplate.find( HQL ); return list ; } public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } }
测试类
package ecut.hibernate; import java.util.Date; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import ecut.hibernate.controller.CustomerController; import ecut.hibernate.entity.Customer; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestCustomerController { private static AbstractApplicationContext container ; public @BeforeClass static void init(){ String configLocations = "classpath:ecut/**/hibernate/beans.xml"; container = new ClassPathXmlApplicationContext( configLocations ); } public @Test void testRegist(){ Customer c = new Customer(); c.setEmail( "lao@ecut.edu.cn" ); c.setPassword( "hello2017" ); Date birthdate = new Date() ; c.setBirthdate( birthdate ); c.setGender( '男' ); c.setNickname( "老王" ); c.setMarried( false ); CustomerController cc = container.getBean( "customerController" , CustomerController.class ); cc.regist( c ); } public @Test void all(){ CustomerController cc = container.getBean( "customerController" , CustomerController.class ); List<Customer> list = cc.allCustomer(); for( Customer c : list ){ System.out.println( c.getEmail() + " : " + c.getNickname() ); } } public @AfterClass static void destory(){ container.close(); } }
通过整合,使数据库的操作得到了简化,Spring的IoC容器则提供了更好的管理方式,它不仅能以声明式的方式配置Session- Factory实例,也可充分利用IoC容器的作用,为SessionFactory注入数据源引用。
转载请于明显处标明出处: