在 jpa hibernate簡單配置 中已經將jpa 和hibernate配置好了,可是依然要咱們來手動管理entityManager, 接下來就要 加入spring的支持,讓spring替咱們來管理 entityManager。java
所用到的jar包:spring
spring 4.0.3 core,api
hibernate 4.2.16(required and jpa),ide
spring-data-commons-1.8.0.RELEASE.jar,ui
spring-data-jpa-1.6.0.RELEASE.jar, (若是是1.7.2版本的會報異常 NoSuchMethod: registerIfNotAlreadyRegistered())spa
commons-logging-1.1.3, .net
slf4j-api-1.7.7hibernate
spring.xmlcode
<?xml version="1.0" encoding="UTF-8"?> <beans ...> <!-- 開啓組件掃描,即spring會掃描 base-package中的類, 將@Component, @Repository, @Service, and @Controller註解的bean掃描到spring上下文中 --> <context:component-scan base-package="com.jt"/> <!-- jpa 的entitymanagerfactory --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <!-- 這個provider也能夠在 persistence.xml 中配置 --> <property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence"></property> </bean> <!-- jpa的事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
注意在 持久層實現中,用 @PersistenceContext 來注入 entityManagercomponent
EmployeeDaoImpl.java
package com.jt.dao.impl; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import com.jt.dao.EmployeeDao; import com.jt.entity.Employee; @Repository public class EmployeeDaoImpl implements EmployeeDao { @PersistenceContext private EntityManager entityManager; @Override public void save(Employee employee) { entityManager.persist(employee); } }
再進一步用spring data jpa簡化,連dao實現都不用寫,讓spring替咱們實現持久層。
在spring.xml加以下配置:
<!-- 讓spring 來實現base-package 中的持久層接口 --> <jpa:repositories base-package="com.jt.dao" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager"></jpa:repositories>
EmployeeDaoJpa.java
package com.jt.dao; import org.springframework.data.repository.Repository; import com.jt.entity.Employee; public interface EmployeeDaoJpa extends Repository<Employee, Integer>{ void save(Employee employee); Employee findByEmployeeId(Integer empId); }
然而,Repository並無提供任何方法,業務模塊多的時候,每個dao都要增刪改查方法,很是麻煩,這時能夠繼承 CrudRepository 內置了10個 CRUD方法,若是須要分頁,能夠繼承 PagingAndSortingRepository。