spring与hibernate的整合
一.导包:
<properties>
<spring-version>4.3.10.RELEASE</spring-version>
<hibernate-version>5.2.11.Final</hibernate-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.4</version>
</dependency>
二.配置spring-context.xml文件和需要引入的数据库连接配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:P="http://www.springframework.org/schema/p" 6 xmlns:util="http://www.springframework.org/schema/util" 7 xmlns:tx="http://www.springframework.org/schema/tx" 8 xmlns:aop="http://www.springframework.org/schema/aop" 9 xsi:schemaLocation="http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans.xsd 11 http://www.springframework.org/schema/context 12 http://www.springframework.org/schema/context/spring-context.xsd 13 http://www.springframework.org/schema/util 14 http://www.springframework.org/schema/util/spring-util.xsd 15 http://www.springframework.org/schema/tx 16 http://www.springframework.org/schema/tx/spring-tx.xsd 17 http://www.springframework.org/schema/aop 18 http://www.springframework.org/schema/aop/spring-aop.xsd"> 19 <context:component-scan base-package="com.yztc.app"/> 20 <bean id="entityManagerFactory" 21 class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" 22 P:dataSource-ref="dataSource" 23 P:packagesToScan="com.yztc.app" 24 P:jpaProperties-ref="jpaProperties" 25 P:persistenceProvider-ref="persistenceProvider" 26 P:jpaVendorAdapter-ref="jpaVendorAdapter" 27 /> 28 <!--数据库连接配置--> 29 <context:property-placeholder location="classpath:config/db.properties"/> 30 <!--适配--> 31 <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 32 <property name="database" value="MYSQL"/> 33 <property name="showSql" value="true"/> 34 <property name="generateDdl" value="true"/> 35 <property name="databasePlatform" value="org.hibernate.dialect.MySQL55Dialect"/> 36 </bean> 37 <bean id="persistenceProvider" class="org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider"> 38 39 </bean> 40 <!--jpa 属性配置--> 41 <util:properties id="jpaProperties"> 42 <!--设置外连接抓取树的最大深度--> 43 <prop key="hibernate.max_fetch_depth">3</prop> 44 <!--查询返回的行数--> 45 <prop key="hibernate.jdbc.fetch_size">50</prop> 46 <!--批量执行sql语句的满25条提交一次--> 47 <prop key="hibernate.jdbc.batch_size">25</prop> 48 <!-- 自动建表类型 validate|create|create-drop|update --> 49 <prop key="hibernate.hbm2ddl.auto">create</prop> 50 <!-- 是否显示SQL --> 51 <prop key="hibernate.show_sql">true</prop> 52 <!-- 显示SQL是否格式化 --> 53 <prop key="hibernate.format_sql">false</prop> 54 <!-- 关闭二级缓存 --> 55 <prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop> 56 <!-- 关闭实体字段映射校验 --> 57 <prop key="javax.persistence.validation.mode">none</prop> 58 </util:properties> 59 <!--第三方的连接池的配置 c3p0 druid--> 60 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 61 <!--JDBC连接串--> 62 <property name="url" value="${jdbc.url}" /> 63 <!--数据库用户名称--> 64 <property name="username" value="${jdbc.username}" /> 65 <!--数据库密码--> 66 <property name="password" value="${jdbc.password}" /> 67 <!-- 连接池最大使用连接数量 --> 68 <property name="maxActive" value="${jdbc.maxActive}"/> 69 <!-- 初始化大小 --> 70 <property name="initialSize" value="${jdbc.initialSize}"/> 71 <!-- 获取连接最大等待时间 --> 72 <property name="maxWait" value="${jdbc.maxWait}"/> 73 <!-- 连接池最小空闲 --> 74 <property name="minIdle" value="${jdbc.minIdle}"/> 75 <!-- 逐出连接的检测时间间隔 --> 76 <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/> 77 <!-- 最小逐出时间 --> 78 <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/> 79 <!-- 测试有效用的SQL Query --> 80 <property name="validationQuery" value="SELECT 'x'"/> 81 <!-- 连接空闲时测试是否有效 --> 82 <property name="testWhileIdle" value="true"/> 83 <!-- 获取连接时测试是否有效 --> 84 <property name="testOnBorrow" value="false"/> 85 <!-- 归还连接时是否测试有效 --> 86 <property name="testOnReturn" value="false"/> 87 </bean> 88 <!--事务--> 89 <bean id="tx" class="org.springframework.orm.jpa.JpaTransactionManager"> 90 <property name="entityManagerFactory" ref="entityManagerFactory"/> 91 </bean> 92 <!--<tx:advice id="advice" transaction-manager="tx">--> 93 <!--<!–crud–>--> 94 <!--<tx:attributes>--> 95 <!--<tx:method name="create*" rollback-for="java.lang.Exception"/>--> 96 <!--<tx:method name="save*" rollback-for="java.lang.Exception"/>--> 97 <!--<tx:method name="update*" rollback-for="java.lang.Exception"/>--> 98 <!--<tx:method name="delete*" rollback-for="java.lang.Exception"/>--> 99 <!--<tx:method name="get*" read-only="true" propagation="SUPPORTS"/>--> 100 <!--<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>--> 101 <!--</tx:attributes>--> 102 <!--</tx:advice>--> 103 <!--<aop:config>--> 104 <!--<aop:pointcut id="pointcut" expression="execution(* com.yztc.app.dao.*.*(..))"/>--> 105 <!--<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>--> 106 <!--</aop:config>--> 107 <tx:annotation-driven transaction-manager="tx" proxy-target-class="true"/> 108 </beans>
1 #数据源连接配置 2 jdbc.url = jdbc:mysql:///hibernate?true&characterEncoding=UTF-8 3 jdbc.username = root 4 jdbc.password = ROOT 5 jdbc.driver =com.mysql.jdbc.Driver 6 #连接池最大使用连接数量 7 jdbc.maxActive=20 8 #初始化大小 9 jdbc.initialSize=2 10 #获得连接最大等待时间 11 jdbc.maxWait=60000 12 #连接池最小空间 13 jdbc.minIdle=0 14 #配置间隔多久才进行一次检测,检测需要关闭的空间连接,单位是毫秒 15 jdbc.timeBetweenEvictionRunsMillis=3000 16 #配置一个连接在池中最小生存的时间,单位是毫秒 17 jdbc.minEvictableIdleTimeMillis=300000
三.创建实体类
1 package com.yztc.app.bean; 2 3 import javax.persistence.Column; 4 import javax.persistence.Entity; 5 import javax.persistence.GeneratedValue; 6 import javax.persistence.Id; 7 8 /** 9 * _ooOoo_ 10 * o8888888o 11 * 88" . "88 12 * (| -_- |) 13 * O\ = /O 14 * ___/`---'\____ 15 * . ' \\| |// `. 16 * / \\||| : |||// \ 17 * / _||||| -:- |||||- \ 18 * | | \\\ - /// | | 19 * | \_| ''\---/'' | | 20 * \ .-\__ `-` ___/-. / 21 * ___`. .' /--.--\ `. . __ 22 * ."" '< `.___\_<|>_/___.' >'"". 23 * | | : `- \`.;`\ _ /`;.`/ - ` : | | 24 * \ \ `-. \_ __\ /__ _/ .-` / / 25 * ======`-.____`-.___\_____/___.-`____.-'====== 26 * `=---=' 27 * ............................................. 28 * 29 * @author bindu 30 * @date 2017-10-23 17:44 31 */ 32 33 @Entity 34 public class User { 35 @Id 36 @GeneratedValue 37 @Column(name = "UID") 38 private Long uid; 39 @Column(name = "NAME",length = 32) 40 private String name; 41 42 43 44 public Long getUid() { 45 return uid; 46 } 47 48 public void setUid(Long uid) { 49 this.uid = uid; 50 } 51 52 public String getName() { 53 return name; 54 } 55 56 public void setName(String name) { 57 this.name = name; 58 } 59 60 public User(String name) { 61 this.name = name; 62 } 63 }
三.dao
package com.yztc.app.dao; import com.yztc.app.bean.User; public interface UserDao { User save1(User user)throws Exception; }
package com.yztc.app.dao; import com.yztc.app.bean.User; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * _ooOoo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ___/`---'\____ * . ' \\| |// `. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' | | * \ .-\__ `-` ___/-. / * ___`. .' /--.--\ `. . __ * ."" '< `.___\_<|>_/___.' >'"". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-'====== * `=---=' * ............................................. * * @author bindu * @date 2017-10-23 17:48 */ @Repository("userDao") public class UserDaoImpl implements UserDao { @PersistenceContext private EntityManager em; @Override @Transactional(rollbackFor = Exception.class ) public User save1(User user) throws Exception { em.persist(user); return null; } }
四.测试类
1 package com.yztc.app; 2 3 import com.yztc.app.bean.User; 4 import com.yztc.app.dao.UserDao; 5 import com.yztc.app.dao.UserDaoImpl; 6 import org.junit.Test; 7 import org.junit.runner.RunWith; 8 import org.springframework.test.context.ContextConfiguration; 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 11 import javax.annotation.Resource; 12 13 /** 14 * _ooOoo_ 15 * o8888888o 16 * 88" . "88 17 * (| -_- |) 18 * O\ = /O 19 * ___/`---'\____ 20 * . ' \\| |// `. 21 * / \\||| : |||// \ 22 * / _||||| -:- |||||- \ 23 * | | \\\ - /// | | 24 * | \_| ''\---/'' | | 25 * \ .-\__ `-` ___/-. / 26 * ___`. .' /--.--\ `. . __ 27 * ."" '< `.___\_<|>_/___.' >'"". 28 * | | : `- \`.;`\ _ /`;.`/ - ` : | | 29 * \ \ `-. \_ __\ /__ _/ .-` / / 30 * ======`-.____`-.___\_____/___.-`____.-'====== 31 * `=---=' 32 * ............................................. 33 * 34 * @author bindu 35 * @date 2017-10-23 17:51 36 */ 37 38 @RunWith(SpringJUnit4ClassRunner.class) 39 @ContextConfiguration("classpath:spring-context.xml") 40 public class TestDao { 41 @Resource 42 UserDao dao; 43 @Test 44 public void testSave() throws Exception { 45 dao.save1(new User("小明涵")); 46 } 47 }