SPRING+JPA+Hibernate配置方法

Posted StrongHan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SPRING+JPA+Hibernate配置方法相关的知识,希望对你有一定的参考价值。

 

1.applicationContext.xml

 1 <?xml version="1.0"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6                         http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
 7                         http://www.springframework.org/schema/context 
 8                         http://www.springframework.org/schema/context/spring-context-4.1.xsd 
10                         http://www.springframework.org/schema/tx 
11                         http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
12 
13     <!-- 扫描目录 -->
14     <context:component-scan base-package="xxx"></context:component-scan>
15     <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
16     <context:property-placeholder location="classpath:jdbc.properties"  ignore-unresolvable="true"/>
17 
18     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
19         destroy-method="close">
20         <property name="driverClass" value="${jdbc.driver}" />
21         <property name="jdbcUrl" value="${jdbc.url}" />
22         <property name="user" value="${jdbc.username}" />
23         <property name="password" value="${jdbc.password}" />
24         <property name="initialPoolSize" value="${connection_pools.initial_pool_size}" />
25         <property name="minPoolSize" value="${connection_pools.min_pool_size}" />
26         <property name="maxPoolSize" value="${connection_pools.max_pool_size}" />
27         <property name="maxIdleTime" value="${connection_pools.max_idle_time}" />
28         <property name="acquireIncrement" value="${connection_pools.acquire_increment}" />
29         <property name="checkoutTimeout" value="${connection_pools.checkout_timeout}" />
30     </bean>
31 
32     <bean id="entityManagerFactory"
33         class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
34         <property name="dataSource" ref="dataSource" />
35         <property name="packagesToScan" value="xxx.entity" />
36         <property name="persistenceProvider">
37             <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
38         </property>
39         <property name="jpaVendorAdapter">
40             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
41                 <property name="generateDdl" value="false" />
42             </bean>
43         </property>
44         <property name="jpaProperties">
45             <props>
46                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
47                 <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
48                 <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
49                 <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
50                 <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
51                 <prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
52                 <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
53                 <prop key="hibernate.hbm2ddl.auto">update</prop>
54                 <prop key="hibernate.show_sql">true</prop>
55                 <prop key="hibernate.format_sql">false</prop>
56                 <prop key="hibernate.use_sql_comments">false</prop>
57                 <prop key="hibernate.connection.isolation">2</prop>
58                 <prop key="javax.persistence.validation.mode">none</prop>
59             </props>
60         </property>
61     </bean>
62 
63     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
64         <property name="entityManagerFactory" ref="entityManagerFactory" />
65     </bean>
66 
67 
68     <!-- 配置 Annotation 驱动,定义事务 -->
69     <tx:annotation-driven transaction-manager="transactionManager"
70         proxy-target-class="false" />
71 
72     <!-- 配置事物自动提交 -->
73 
74 </beans>

 

2. BaseDao

1 public interface BaseDao<T, ID extends Serializable> {
2 /**
3 省略
4 */
5 }

 

3. BaseDaoImpl

 1 import java.io.Serializable;
 2 import java.lang.reflect.ParameterizedType;
 3 import java.lang.reflect.Type;
 4 
 5 import javax.persistence.EntityManager;
 6 import javax.persistence.FlushModeType;
 7 import javax.persistence.LockModeType;
 8 import javax.persistence.PersistenceContext;
 9 
10 import javax.transaction.Transactional;
11 
12 import org.apache.commons.lang.StringUtils;
13 import org.springframework.stereotype.Repository;
14 import org.springframework.util.Assert;
15 
16 @Transactional
17 @Repository
18 public abstract class BaseDaoImpl<T, ID extends Serializable> implements BaseDao<T, ID> {
19 
20     /** 实体类类型 */
21     private Class<T> entityClass;
22     
23 
24     @PersistenceContext
25     protected EntityManager entityManager;
26     
27     
28     @SuppressWarnings("unchecked")
29     public BaseDaoImpl() {
30         Type type = getClass().getGenericSuperclass();
31         Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
32         entityClass = (Class<T>) parameterizedType[0];
33     }
34 
35     public T find(ID id) {
36         if (id != null) {
37             return entityManager.find(entityClass, id);
38         }
39         return null;
40     }
41 
42 
43 public List<T> findList(Integer first, Integer count, List<Filter> filters, List<Order> orders) {
44         CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
45         CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityClass);
46         criteriaQuery.select(criteriaQuery.from(entityClass));
47         return findList(criteriaQuery, first, count, filters, orders);
48     }
49 
50     public Page<T> findPage(Pageable pageable) {
51         CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
52         CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityClass);
53         criteriaQuery.select(criteriaQuery.from(entityClass));
54         return findPage(criteriaQuery, pageable);
55     }
56 
57 
58 public void persist(T entity) {
59         Assert.notNull(entity);
60         
61         entityManager.persist(entity);
62     }
63 
64     public T merge(T entity) {
65         Assert.notNull(entity);
66         return entityManager.merge(entity);
67     }
68 
69     public void remove(T entity) {
70         if (entity != null) {
71             entityManager.remove(entity);
72         }
73     }
74 
75     public void refresh(T entity) {
76         if (entity != null) {
77             entityManager.refresh(entity);
78         }
79     }
80 /**
81 省略 82 */83 }

 

4 Common Dao

1 import org.springframework.stereotype.Repository;
2 
3 
4 @Repository
5 public class EmployeeDAO extends BaseDaoImpl<EmployeeEntity, Long>  {
6  public void save(EmployeeEntity entity){
7      persist(entity);
8  }
9 }

 

5 Entity

 1 import javax.persistence.Column;
 2 import javax.persistence.Entity;
 3 import javax.persistence.Table;
 4 import javax.persistence.GeneratedValue;
 5 import javax.persistence.Id;
 6 
 7 @Entity
 8 @Table(name = "employee")
 9 public class EmployeeEntity  {
10 
11 @Id
12 @GeneratedValue(strategy = GenerationType.AUTO)
13 @Column(name="staffid")
14 private Long id;
15 
16 /**
17 省略
18 */
19 }

 

以上是关于SPRING+JPA+Hibernate配置方法的主要内容,如果未能解决你的问题,请参考以下文章

spring-data-jpa+hibernate 各种缓存的配置演示

Spring Boot / JPA / Hibernate,如何根据 Spring 配置文件切换数据库供应商?

如何配置 Spring 使 JPA(Hibernate)和 JDBC(JdbcTemplate 或 MyBatis)共享同一个事务

JPA事务不生效原因

JPA hibernate spring repository pgsql java 工程:sql文件导入数据,测试数据

使用 Hibernate 4、Spring 3、JPA 2 配置 MySQL5 最终有 1 个异常