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

Spring整合JPA與Hibernate流程詳解

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

設置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 相關的屬性 -->
          <!-- 配置數(shù)據(jù)庫類型 -->
         <property name="database" value="MYSQL"/>
         <!-- 顯示執(zhí)行的 SQL -->
         <property name="showSql" value="true"/>
      </bean>
    </property>
    <!-- 配置Spring所掃描的實體類所在的包 -->
    <property name="packagesToScan">
      <list>
        <value>mypack</value>
      </list>
    </property>
  </bean>
  <!-- 配置事務管理器 -->
  <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" />
    <!-- 配置開啟由注解驅動的事務處理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
     <!-- 配置Spring需要掃描的包,
         Spring會掃描這些包以及子包中類的Spring注解 -->
     <context:component-scan base-package="mypack"/>
</beans>

applicationContext.xml配置文件的<context:property-placeholder>元素設定屬性文件為classpath根路徑下的jdbc.properties文件。C3P0數(shù)據(jù)源會從該屬性文件獲取連接數(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組件時,指定使用HibernateJpaVendorAdapter適配器,該適配器能夠把Hibernate集成到Spring中。<property name="packagesToScan">屬性指定實體類所在的包,Spring會掃描這些包中實體類中的對象-關系映射注解。

applicationContext.xml配置文件的<tx:annotation-driven>元素表明在程序中可以通過@Transactional注解來為委托Spring為一個方法聲明事務邊界。

編寫范例的Java類

本范例運用了Spring框架,把業(yè)務邏輯層又細分為業(yè)務邏輯服務層、數(shù)據(jù)訪問層和模型層。

在上圖中,模型層包含了表示業(yè)務數(shù)據(jù)的實體類,數(shù)據(jù)訪問層負責訪問數(shù)據(jù)庫,業(yè)務邏輯服務層負責處理各種業(yè)務邏輯,并且通過數(shù)據(jù)訪問層提供的方法來完成對數(shù)據(jù)庫的各種操作。CustomerDaoImpl類、CustomerServiceImpl類和Tester類都會用到Spring API中的類或者注解。其余的類和接口則不依賴Spring API。

編寫Customer實體類

Customer類是普通的實體類,它不依賴Sping API,但是會通過JPA API和Hibernate API中的注解來設置對象-關系映射。以下是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類的構造方法、set方法和get方法
  …
}

編寫CustomerDao數(shù)據(jù)訪問接口和類

CustomerDao為DAO(Data Access Object,數(shù)據(jù)訪問對象)接口,提供了與Customer對象有關的訪問數(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類實現(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的兩個注解。

(1)@Repository注解:表明CustomerDaoImpl是DAO類,在Spring的applicationContext.xml文件中通過<bean>元素配置了這個Bean組件,Spring會負責創(chuàng)建該Bean組件,并管理它的生命周期,如:

<bean id="CustomerDao"class="mypack.CustomerDaoImpl"/>

(2)@PersistenceContext注解:表明CustomerDaoImpl類的entityManager屬性由Spring來提供,Spring會負責創(chuàng)建并管理EntityManager對象的生命周期。Spring會根據(jù)@PersistenceContext(name="entityManagerFactory")注解中設置的EntityManagerFactory對象來創(chuàng)建EntityManager對象,而EntityManagerFactory對象作為Bean組件,在applicationContext.xml文件中也通過<bean>元素做了配置,EntityManagerFactory對象的生命周期也由Spring來管理。

從CustomerDaoImpl類的源代碼可以看出,這個類無須管理EntityManagerFactory和EntityManager對象的生命周期,只需用Spring API的@Repository和@PersistenceContext注解來標識,Spring 就會自動管理這兩個對象的生命周期。

在applicationContext.xml配置文件中 ,<context:component-scan>元素指定Spring所掃描的包,Spring會掃描指定的包以及子包中的所有類中的Spring注解,提供和注解對應的功能。

編寫CustomerService業(yè)務邏輯服務接口和類

CustomerService接口作為業(yè)務邏輯服務接口,會包含一些處理業(yè)務邏輯的操作。本范例做了簡化,CustomerService接口負責保存、更新、刪除和檢索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類實現(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的三個注解。

(1)@Service注解:表明CustomerServiceImpl類是服務類。在Spring的applicationContext.xml文件中通過<bean>元素配置了這個Bean組件,Spring會負責創(chuàng)建該Bean組件,并管理它的生命周期,如:

<bean id="CustomerService"class="mypack.CustomerServiceImpl"/>

(2)@Autowired注解:表明customerDao屬性由Spring來提供。

(3)@Transactional注解:表明被注解的方法是事務型的方法。Spring將該方法中的所有操作加入到事務中。

從CustomerServiceImpl類的源代碼可以看出,CustomerServiceImpl類雖然依賴CustomerDao組件,但是無須創(chuàng)建和管理它的生命周期,而且CustomerServiceImpl類也無須顯式聲明事務邊界。這些都由Spring代勞了。

編寫測試類Tester

Tester類是測試程序,它會初始化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類的構造方法中,首先根據(jù)applicationContext.xml配置文件的內(nèi)容,來初始化Spring框架,并且創(chuàng)建了一個ClassPathXmlApplicationContext對象,再調用這個對象的getBean(CustomerService.class)方法,就能獲得CustomerService組件。

到此這篇關于Spring整合JPA與Hibernate流程詳解的文章就介紹到這了,更多相關Spring整合JPA與Hibernate內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

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

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

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

    Java中的 BigDecimal 和 String 的相互轉換問題

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

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

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

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

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

    spring使用RedisTemplate的操作類訪問Redis

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

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

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

    手把手帶你用java搞定青蛙跳臺階

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

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

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

    Java畫筆的簡單實用方法

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

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

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

最新評論

都安| 托里县| 民权县| 兴安县| 东源县| 明溪县| 高安市| 连平县| 象州县| 闻喜县| 柳州市| 开远市| 新绛县| 桐城市| 嘉禾县| 曲松县| 克什克腾旗| 乐山市| 古蔺县| 聂荣县| 岐山县| 峨眉山市| 鄂温| 新晃| 遵化市| 娱乐| 连江县| 和政县| 昭觉县| 周宁县| 陵川县| 沁阳市| 阿荣旗| 图片| 年辖:市辖区| 闵行区| 嵩明县| 剑川县| 吉隆县| 泽州县| 兴国县|