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ù)庫連接池 --> <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ù)庫類型 --> <property name="database" value="MYSQL"/> <!-- 顯示執(zhí)行的 SQL --> <property name="showSql" value="true"/> </bean> </property> <!-- 配置Spring所掃描的實(shí)體類所在的包 --> <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" /> <!-- 配置開啟由注解驅(qū)動(dòng)的事務(wù)處理 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置Spring需要掃描的包, Spring會(huì)掃描這些包以及子包中類的Spring注解 --> <context:component-scan base-package="mypack"/> </beans>
applicationContext.xml配置文件的<context:property-placeholder>元素設(shè)定屬性文件為classpath根路徑下的jdbc.properties文件。C3P0數(shù)據(jù)源會(huì)從該屬性文件獲取連接數(shù)據(jù)庫的信息。以下是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í)體類所在的包,Spring會(huì)掃描這些包中實(shí)體類中的對象-關(guān)系映射注解。
applicationContext.xml配置文件的<tx:annotation-driven>元素表明在程序中可以通過@Transactional注解來為委托Spring為一個(gè)方法聲明事務(wù)邊界。
編寫范例的Java類
本范例運(yùn)用了Spring框架,把業(yè)務(wù)邏輯層又細(xì)分為業(yè)務(wù)邏輯服務(wù)層、數(shù)據(jù)訪問層和模型層。
在上圖中,模型層包含了表示業(yè)務(wù)數(shù)據(jù)的實(shí)體類,數(shù)據(jù)訪問層負(fù)責(zé)訪問數(shù)據(jù)庫,業(yè)務(wù)邏輯服務(wù)層負(fù)責(zé)處理各種業(yè)務(wù)邏輯,并且通過數(shù)據(jù)訪問層提供的方法來完成對數(shù)據(jù)庫的各種操作。CustomerDaoImpl類、CustomerServiceImpl類和Tester類都會(huì)用到Spring API中的類或者注解。其余的類和接口則不依賴Spring API。
編寫Customer實(shí)體類
Customer類是普通的實(shí)體類,它不依賴Sping API,但是會(huì)通過JPA API和Hibernate API中的注解來設(shè)置對象-關(guān)系映射。以下是Customer類的源代碼。
/* 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類的構(gòu)造方法、set方法和get方法 … }
編寫CustomerDao數(shù)據(jù)訪問接口和類
CustomerDao為DAO(Data Access Object,數(shù)據(jù)訪問對象)接口,提供了與Customer對象有關(guān)的訪問數(shù)據(jù)庫的各種方法。以下是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類實(shí)現(xiàn)了CustomerDao接口,通過Spring API和JPA API來訪問數(shù)據(jù)庫。以下是CustomerDaoImpl類的源代碼。
/* 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類中使用了以下來自Spring API的兩個(gè)注解。
(1)@Repository注解:表明CustomerDaoImpl是DAO類,在Spring的applicationContext.xml文件中通過<bean>元素配置了這個(gè)Bean組件,Spring會(huì)負(fù)責(zé)創(chuàng)建該Bean組件,并管理它的生命周期,如:
<bean id="CustomerDao"class="mypack.CustomerDaoImpl"/>
(2)@PersistenceContext注解:表明CustomerDaoImpl類的entityManager屬性由Spring來提供,Spring會(huì)負(fù)責(zé)創(chuàng)建并管理EntityManager對象的生命周期。Spring會(huì)根據(jù)@PersistenceContext(name="entityManagerFactory")注解中設(shè)置的EntityManagerFactory對象來創(chuàng)建EntityManager對象,而EntityManagerFactory對象作為Bean組件,在applicationContext.xml文件中也通過<bean>元素做了配置,EntityManagerFactory對象的生命周期也由Spring來管理。
從CustomerDaoImpl類的源代碼可以看出,這個(gè)類無須管理EntityManagerFactory和EntityManager對象的生命周期,只需用Spring API的@Repository和@PersistenceContext注解來標(biāo)識(shí),Spring 就會(huì)自動(dòng)管理這兩個(gè)對象的生命周期。
在applicationContext.xml配置文件中 ,<context:component-scan>元素指定Spring所掃描的包,Spring會(huì)掃描指定的包以及子包中的所有類中的Spring注解,提供和注解對應(yīng)的功能。
編寫CustomerService業(yè)務(wù)邏輯服務(wù)接口和類
CustomerService接口作為業(yè)務(wù)邏輯服務(wù)接口,會(huì)包含一些處理業(yè)務(wù)邏輯的操作。本范例做了簡化,CustomerService接口負(fù)責(zé)保存、更新、刪除和檢索Customer對象,以下是它的源代碼。
/* 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類實(shí)現(xiàn)了CustomerService接口,通過CustomerDao組件來訪問數(shù)據(jù)庫,以下是它的源代碼。
/* 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類中使用了以下來自Spring API的三個(gè)注解。
(1)@Service注解:表明CustomerServiceImpl類是服務(wù)類。在Spring的applicationContext.xml文件中通過<bean>元素配置了這個(gè)Bean組件,Spring會(huì)負(fù)責(zé)創(chuàng)建該Bean組件,并管理它的生命周期,如:
<bean id="CustomerService"class="mypack.CustomerServiceImpl"/>
(2)@Autowired注解:表明customerDao屬性由Spring來提供。
(3)@Transactional注解:表明被注解的方法是事務(wù)型的方法。Spring將該方法中的所有操作加入到事務(wù)中。
從CustomerServiceImpl類的源代碼可以看出,CustomerServiceImpl類雖然依賴CustomerDao組件,但是無須創(chuàng)建和管理它的生命周期,而且CustomerServiceImpl類也無須顯式聲明事務(wù)邊界。這些都由Spring代勞了。
編寫測試類Tester
Tester類是測試程序,它會(huì)初始化Spring框架,并訪問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類的構(gòu)造方法中,首先根據(jù)applicationContext.xml配置文件的內(nèi)容,來初始化Spring框架,并且創(chuàng)建了一個(gè)ClassPathXmlApplicationContext對象,再調(diào)用這個(gè)對象的getBean(CustomerService.class)方法,就能獲得CustomerService組件。
到此這篇關(guān)于Spring整合JPA與Hibernate流程詳解的文章就介紹到這了,更多相關(guān)Spring整合JPA與Hibernate內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
dom4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄猟om4j創(chuàng)建和解析xml文檔的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-06-06Spring Data JPA中 in 條件參數(shù)的傳遞方式
這篇文章主要介紹了Spring Data JPA中 in 條件參數(shù)的傳遞方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06Spring Security實(shí)現(xiàn)多次登錄失敗后賬戶鎖定功能
當(dāng)用戶多次登錄失敗的時(shí)候,我們應(yīng)該將賬戶鎖定,等待一定的時(shí)間之后才能再次進(jìn)行登錄操作。今天小編給大家分享Spring Security實(shí)現(xiàn)多次登錄失敗后賬戶鎖定功能,感興趣的朋友一起看看吧2019-11-11Java網(wǎng)絡(luò)編程之UDP實(shí)現(xiàn)原理解析
UDP實(shí)現(xiàn)通信非常簡單,沒有服務(wù)器,每個(gè)都是客戶端,每個(gè)客戶端都需要一個(gè)發(fā)送端口和一個(gè)接收端口,本文給大家介紹Java網(wǎng)絡(luò)編程之UDP實(shí)現(xiàn)原理解析,感興趣的朋友一起看看吧2021-09-09IDEA實(shí)現(xiàn) springmvc的簡單注冊登錄功能的示例代碼
這篇文章主要介紹了IDEA實(shí)現(xiàn) springmvc的簡單注冊登錄功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06Spring 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),本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07