最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring整合JPA與Hibernate流程詳解

 更新時(shí)間:2023年01月09日 09:56:40   作者:TiAmo zhang  
這篇文章主要介紹了Spring整合Hibernate與JPA,在正式進(jìn)入Hibernate的高級應(yīng)用之前,需要了解聲明是數(shù)據(jù)模型與領(lǐng)域模型,這兩個(gè)概念將會(huì)幫助我們更好的理解實(shí)體對象的關(guān)聯(lián)關(guān)系映射

設(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)識,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)文章

  • 使用Java實(shí)現(xiàn)文件夾的遍歷操作指南

    使用Java實(shí)現(xiàn)文件夾的遍歷操作指南

    網(wǎng)上大多采用java遞歸的方式遍歷文件夾下的文件,這里我不太喜歡遞歸的風(fēng)格,這篇文章主要給大家介紹了關(guān)于使用Java實(shí)現(xiàn)文件夾的遍歷操作的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-05-05
  • Java中的 BigDecimal 和 String 的相互轉(zhuǎn)換問題

    Java中的 BigDecimal 和 String 的相互轉(zhuǎn)換問題

    這篇文章主要介紹了Java中的 BigDecimal 和 String 的相互轉(zhuǎn)換問題,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-05-05
  • Java使用Hutool實(shí)現(xiàn)AES、DES加密解密的方法

    Java使用Hutool實(shí)現(xiàn)AES、DES加密解密的方法

    本篇文章主要介紹了Java使用Hutool實(shí)現(xiàn)AES、DES加密解密的方法,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-08-08
  • Intellij IDEA 添加jar包的三種方式(小結(jié))

    Intellij IDEA 添加jar包的三種方式(小結(jié))

    這篇文章主要介紹了Intellij IDEA 添加jar包的三種方式(小結(jié)),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-08-08
  • spring使用RedisTemplate的操作類訪問Redis

    spring使用RedisTemplate的操作類訪問Redis

    本篇文章主要介紹了spring使用RedisTemplate的操作類訪問Redis,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • 基于Java class對象說明、Java 靜態(tài)變量聲明和賦值說明(詳解)

    基于Java class對象說明、Java 靜態(tài)變量聲明和賦值說明(詳解)

    下面小編就為大家?guī)硪黄贘ava class對象說明、Java 靜態(tài)變量聲明和賦值說明(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-06-06
  • 手把手帶你用java搞定青蛙跳臺(tái)階

    手把手帶你用java搞定青蛙跳臺(tái)階

    這篇文章主要給大家介紹了關(guān)于Java青蛙跳臺(tái)階問題的解決思路與代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-08-08
  • Java并發(fā)編程示例(九):本地線程變量的使用

    Java并發(fā)編程示例(九):本地線程變量的使用

    這篇文章主要介紹了Java并發(fā)編程示例(九):本地線程變量的使用,有時(shí),我們更希望能在線程內(nèi)單獨(dú)使用,而不和其他使用同一對象啟動(dòng)的線程共享,Java并發(fā)接口提供了一種很清晰的機(jī)制來滿足此需求,該機(jī)制稱為本地線程變量,需要的朋友可以參考下
    2014-12-12
  • Java畫筆的簡單實(shí)用方法

    Java畫筆的簡單實(shí)用方法

    這篇文章主要介紹了Java畫筆的簡單實(shí)用方法,需要的朋友可以參考下
    2017-09-09
  • 淺談java線程狀態(tài)與線程安全解析

    淺談java線程狀態(tài)與線程安全解析

    本文主要介紹了淺談java線程狀態(tài)與線程安全解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02

最新評論

天台县| 揭西县| 汉沽区| 三门峡市| 成武县| 大足县| 紫金县| 油尖旺区| 马龙县| 红桥区| 叙永县| 金川县| 金华市| 桑日县| 镇平县| 天气| 新民市| 浦县| 商丘市| 七台河市| 颍上县| 建平县| 德昌县| 青冈县| 遂川县| 丽江市| 大姚县| 西城区| 宜宾市| 忻城县| 襄汾县| 巴林左旗| 井冈山市| 南雄市| 昭苏县| 中超| 行唐县| 廉江市| 河源市| 孝感市| 体育|