Spring整合JPA與Hibernate流程詳解
設(shè)置Spring的配置文件
在Spring的配置文件applicationContext.xml中,配置C3P0數(shù)據(jù)源、EntityManagerFactory和JpaTransactionManager等Bean組件。以下是applicationContext.xml文件的源程序。
/* applicationContext.xml */
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=…>
<!-- 配置屬性文件的文件路徑 -->
<context:property-placeholder
location="classpath:jdbc.properties"/>
<!-- 配置C3P0數(shù)據(jù)庫(kù)連接池 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver.class}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- Spring 整合 JPA,配置 EntityManagerFactory-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa
.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor
.HibernateJpaVendorAdapter">
<!-- Hibernate 相關(guān)的屬性 -->
<!-- 配置數(shù)據(jù)庫(kù)類(lèi)型 -->
<property name="database" value="MYSQL"/>
<!-- 顯示執(zhí)行的 SQL -->
<property name="showSql" value="true"/>
</bean>
</property>
<!-- 配置Spring所掃描的實(shí)體類(lèi)所在的包 -->
<property name="packagesToScan">
<list>
<value>mypack</value>
</list>
</property>
</bean>
<!-- 配置事務(wù)管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory"/>
</bean>
<bean id="CustomerService" class="mypack.CustomerServiceImpl" />
<bean id="CustomerDao" class="mypack.CustomerDaoImpl" />
<!-- 配置開(kāi)啟由注解驅(qū)動(dòng)的事務(wù)處理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置Spring需要掃描的包,
Spring會(huì)掃描這些包以及子包中類(lèi)的Spring注解 -->
<context:component-scan base-package="mypack"/>
</beans>applicationContext.xml配置文件的<context:property-placeholder>元素設(shè)定屬性文件為classpath根路徑下的jdbc.properties文件。C3P0數(shù)據(jù)源會(huì)從該屬性文件獲取連接數(shù)據(jù)庫(kù)的信息。以下是jdbc.properties文件的源代碼。
/* jdbc.properties */
jdbc.username=root
jdbc.password=1234
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sampledb?useSSL=false
Spring的applicationContext.xml配置文件在配置EntityManagerFactory Bean組件時(shí),指定使用HibernateJpaVendorAdapter適配器,該適配器能夠把Hibernate集成到Spring中。<property name="packagesToScan">屬性指定實(shí)體類(lèi)所在的包,Spring會(huì)掃描這些包中實(shí)體類(lèi)中的對(duì)象-關(guān)系映射注解。
applicationContext.xml配置文件的<tx:annotation-driven>元素表明在程序中可以通過(guò)@Transactional注解來(lái)為委托Spring為一個(gè)方法聲明事務(wù)邊界。
編寫(xiě)范例的Java類(lèi)
本范例運(yùn)用了Spring框架,把業(yè)務(wù)邏輯層又細(xì)分為業(yè)務(wù)邏輯服務(wù)層、數(shù)據(jù)訪(fǎng)問(wèn)層和模型層。

在上圖中,模型層包含了表示業(yè)務(wù)數(shù)據(jù)的實(shí)體類(lèi),數(shù)據(jù)訪(fǎng)問(wèn)層負(fù)責(zé)訪(fǎng)問(wèn)數(shù)據(jù)庫(kù),業(yè)務(wù)邏輯服務(wù)層負(fù)責(zé)處理各種業(yè)務(wù)邏輯,并且通過(guò)數(shù)據(jù)訪(fǎng)問(wèn)層提供的方法來(lái)完成對(duì)數(shù)據(jù)庫(kù)的各種操作。CustomerDaoImpl類(lèi)、CustomerServiceImpl類(lèi)和Tester類(lèi)都會(huì)用到Spring API中的類(lèi)或者注解。其余的類(lèi)和接口則不依賴(lài)Spring API。
編寫(xiě)Customer實(shí)體類(lèi)
Customer類(lèi)是普通的實(shí)體類(lèi),它不依賴(lài)Sping API,但是會(huì)通過(guò)JPA API和Hibernate API中的注解來(lái)設(shè)置對(duì)象-關(guān)系映射。以下是Customer類(lèi)的源代碼。
/* Customer.java */
@Entity
@Table(name="CUSTOMERS")
public class Customer implements java.io.Serializable {
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
@Column(name="ID")
private Long id;
@Column(name="NAME")
private String name;
@Column(name="AGE")
private int age;
//此處省略Customer類(lèi)的構(gòu)造方法、set方法和get方法
…
}編寫(xiě)CustomerDao數(shù)據(jù)訪(fǎng)問(wèn)接口和類(lèi)
CustomerDao為DAO(Data Access Object,數(shù)據(jù)訪(fǎng)問(wèn)對(duì)象)接口,提供了與Customer對(duì)象有關(guān)的訪(fǎng)問(wèn)數(shù)據(jù)庫(kù)的各種方法。以下是CustomerDao接口的源代碼。
/* CustomerDao.java */
public interface CustomerDao {
public void insertCustomer(Customer customer);
public void updateCustomer(Customer customer);
public void deleteCustomer(Customer customer);
public Customer findCustomerById(Long customerId);
public List<Customer>findCustomerByName(String name);
}CustomerDaoImpl類(lèi)實(shí)現(xiàn)了CustomerDao接口,通過(guò)Spring API和JPA API來(lái)訪(fǎng)問(wèn)數(shù)據(jù)庫(kù)。以下是CustomerDaoImpl類(lèi)的源代碼。
/* CustomerDaoImpl.java */
package mypack;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Repository("CustomerDao")
public class CustomerDaoImpl implements CustomerDao {
@PersistenceContext(name="entityManagerFactory")
private EntityManager entityManager;
public void insertCustomer(Customer customer) {
entityManager.persist(customer);
}
public void updateCustomer(Customer customer) {
entityManager.merge(customer);
}
public void deleteCustomer(Customer customer) {
Customer c = findCustomerById(customer.getId());
entityManager.remove(c);
}
public Customer findCustomerById(Long customerId) {
return entityManager.find(Customer.class, customerId);
}
public List<Customer> findCustomerByName(String name) {
return entityManager
.createQuery("from Customer c where c.name = :name",
Customer.class)
.setParameter("name", name)
.getResultList();
}
}在CustomerDaoImpl類(lèi)中使用了以下來(lái)自Spring API的兩個(gè)注解。
(1)@Repository注解:表明CustomerDaoImpl是DAO類(lèi),在Spring的applicationContext.xml文件中通過(guò)<bean>元素配置了這個(gè)Bean組件,Spring會(huì)負(fù)責(zé)創(chuàng)建該Bean組件,并管理它的生命周期,如:
<bean id="CustomerDao"class="mypack.CustomerDaoImpl"/>
(2)@PersistenceContext注解:表明CustomerDaoImpl類(lèi)的entityManager屬性由Spring來(lái)提供,Spring會(huì)負(fù)責(zé)創(chuàng)建并管理EntityManager對(duì)象的生命周期。Spring會(huì)根據(jù)@PersistenceContext(name="entityManagerFactory")注解中設(shè)置的EntityManagerFactory對(duì)象來(lái)創(chuàng)建EntityManager對(duì)象,而EntityManagerFactory對(duì)象作為Bean組件,在applicationContext.xml文件中也通過(guò)<bean>元素做了配置,EntityManagerFactory對(duì)象的生命周期也由Spring來(lái)管理。
從CustomerDaoImpl類(lèi)的源代碼可以看出,這個(gè)類(lèi)無(wú)須管理EntityManagerFactory和EntityManager對(duì)象的生命周期,只需用Spring API的@Repository和@PersistenceContext注解來(lái)標(biāo)識(shí),Spring 就會(huì)自動(dòng)管理這兩個(gè)對(duì)象的生命周期。
在applicationContext.xml配置文件中 ,<context:component-scan>元素指定Spring所掃描的包,Spring會(huì)掃描指定的包以及子包中的所有類(lèi)中的Spring注解,提供和注解對(duì)應(yīng)的功能。
編寫(xiě)CustomerService業(yè)務(wù)邏輯服務(wù)接口和類(lèi)
CustomerService接口作為業(yè)務(wù)邏輯服務(wù)接口,會(huì)包含一些處理業(yè)務(wù)邏輯的操作。本范例做了簡(jiǎn)化,CustomerService接口負(fù)責(zé)保存、更新、刪除和檢索Customer對(duì)象,以下是它的源代碼。
/* CustomerService.java */
public interface CustomerService {
public void insertCustomer(Customer customer);
public void updateCustomer(Customer customer);
public Customer findCustomerById(Long customerId);
public void deleteCustomer(Customer customer);
public List<Customer> findCustomerByName(String name);
}CustomerServiceImpl類(lèi)實(shí)現(xiàn)了CustomerService接口,通過(guò)CustomerDao組件來(lái)訪(fǎng)問(wèn)數(shù)據(jù)庫(kù),以下是它的源代碼。
/* CustomerServiceImpl.java */
package mypack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service("CustomerService")
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerDao customerDao;
@Transactional
public void insertCustomer(Customer customer){
customerDao.insertCustomer(customer);
}
@Transactional
public void updateCustomer(Customer customer){
customerDao.updateCustomer(customer);
}
@Transactional
public Customer findCustomerById(Long customerId){
return customerDao.findCustomerById(customerId);
}
@Transactional
public void deleteCustomer(Customer customer){
customerDao.deleteCustomer(customer);
}
@Transactional
public List<Customer> findCustomerByName(String name){
return customerDao.findCustomerByName(name);
}
}在CustomerServiceImpl類(lèi)中使用了以下來(lái)自Spring API的三個(gè)注解。
(1)@Service注解:表明CustomerServiceImpl類(lèi)是服務(wù)類(lèi)。在Spring的applicationContext.xml文件中通過(guò)<bean>元素配置了這個(gè)Bean組件,Spring會(huì)負(fù)責(zé)創(chuàng)建該Bean組件,并管理它的生命周期,如:
<bean id="CustomerService"class="mypack.CustomerServiceImpl"/>
(2)@Autowired注解:表明customerDao屬性由Spring來(lái)提供。
(3)@Transactional注解:表明被注解的方法是事務(wù)型的方法。Spring將該方法中的所有操作加入到事務(wù)中。
從CustomerServiceImpl類(lèi)的源代碼可以看出,CustomerServiceImpl類(lèi)雖然依賴(lài)CustomerDao組件,但是無(wú)須創(chuàng)建和管理它的生命周期,而且CustomerServiceImpl類(lèi)也無(wú)須顯式聲明事務(wù)邊界。這些都由Spring代勞了。
編寫(xiě)測(cè)試類(lèi)Tester
Tester類(lèi)是測(cè)試程序,它會(huì)初始化Spring框架,并訪(fǎng)問(wèn)CustomerService組件,以下是它的源代碼。
/* Tester.java */
package mypack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support
.ClassPathXmlApplicationContext;
import java.util.List;
public class Tester{
private ApplicationContext ctx = null;
private CustomerService customerService = null;
public Tester(){
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
customerService = ctx.getBean(CustomerService.class);
}
public void test(){
Customer customer=new Customer("Tom",25);
customerService.insertCustomer(customer);
customer.setAge(36);
customerService.updateCustomer(customer);
Customer c=customerService.findCustomerById(customer.getId());
System.out.println(c.getName()+": "+c.getAge()+"歲");
List<Customer> customers=
customerService.findCustomerByName(c.getName());
for(Customer cc:customers)
System.out.println(cc.getName()+": "+cc.getAge()+"歲");
customerService.deleteCustomer(customer);
}
public static void main(String args[]) throws Exception {
new Tester().test();
}
}在Tester類(lèi)的構(gòu)造方法中,首先根據(jù)applicationContext.xml配置文件的內(nèi)容,來(lái)初始化Spring框架,并且創(chuàng)建了一個(gè)ClassPathXmlApplicationContext對(duì)象,再調(diào)用這個(gè)對(duì)象的getBean(CustomerService.class)方法,就能獲得CustomerService組件。
到此這篇關(guān)于Spring整合JPA與Hibernate流程詳解的文章就介紹到這了,更多相關(guān)Spring整合JPA與Hibernate內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot整合JPA框架實(shí)現(xiàn)過(guò)程講解
- Springboot整合JPA配置多數(shù)據(jù)源流程詳解
- Spring?Boot整合持久層之JPA多數(shù)據(jù)源
- Spring?Boot?整合持久層之Spring Data JPA
- SpringBoot整合Hibernate Validator實(shí)現(xiàn)參數(shù)驗(yàn)證功能
- Spring5+SpringMvc+Hibernate5整合的實(shí)現(xiàn)
- Spring+SpringMVC+Hibernate整合實(shí)例講解
- Spring和Hibernate的整合操作示例
相關(guān)文章
dom4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇dom4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
Spring Data JPA中 in 條件參數(shù)的傳遞方式
這篇文章主要介紹了Spring Data JPA中 in 條件參數(shù)的傳遞方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Spring Security實(shí)現(xiàn)多次登錄失敗后賬戶(hù)鎖定功能
當(dāng)用戶(hù)多次登錄失敗的時(shí)候,我們應(yīng)該將賬戶(hù)鎖定,等待一定的時(shí)間之后才能再次進(jìn)行登錄操作。今天小編給大家分享Spring Security實(shí)現(xiàn)多次登錄失敗后賬戶(hù)鎖定功能,感興趣的朋友一起看看吧2019-11-11
Java網(wǎng)絡(luò)編程之UDP實(shí)現(xiàn)原理解析
UDP實(shí)現(xiàn)通信非常簡(jiǎn)單,沒(méi)有服務(wù)器,每個(gè)都是客戶(hù)端,每個(gè)客戶(hù)端都需要一個(gè)發(fā)送端口和一個(gè)接收端口,本文給大家介紹Java網(wǎng)絡(luò)編程之UDP實(shí)現(xiàn)原理解析,感興趣的朋友一起看看吧2021-09-09
IDEA實(shí)現(xiàn) springmvc的簡(jiǎn)單注冊(cè)登錄功能的示例代碼
這篇文章主要介紹了IDEA實(shí)現(xiàn) springmvc的簡(jiǎn)單注冊(cè)登錄功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
Spring gateway配置Spring Security實(shí)現(xiàn)統(tǒng)一權(quán)限驗(yàn)證與授權(quán)示例源碼
這篇文章主要介紹了Spring gateway配置Spring Security實(shí)現(xiàn)統(tǒng)一權(quán)限驗(yàn)證與授權(quán),本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
淺談java 單例模式DCL的缺陷及單例的正確寫(xiě)法
這篇文章主要介紹了淺談java 單例模式DCL的缺陷及單例的正確寫(xiě)法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09

