>>分享孙卫琴的Java技术专稿和著作 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 15095 个阅读者 刷新本主题
 * 贴子主题:  【持久化专题】JPA API的基本用法 回复文章 点赞(0)  收藏  
作者:sunweiqin    发表时间:2021-05-05 09:54:41     消息  查看  搜索  好友  邮件  复制  引用

本文参考《精通JPA与Hibernate:Java对象持久化技术详解》,作者:孙卫琴,清华大学出版社出版

Hibernate API和JPA API中主要接口之间有一些对应关系,例如:
JPA API ----------------------- Hibernate API
EntityManagerFactory ----- SessionFactory
EntityManager ---------------- Session
EntityTransaction ------------- Transaction

     SessionFactory接口在JPA API中的对等接口是javax.persistence.EntityManagerFactory;Session接口在JPA API中的对等接口是javax.persistence.EntityManager;Transaction接口在JPA API中的对等接口是javax.persistence.EntityTransaction。Query接口在JPA API中的对等接口是javax.persistence.Query。

     EntityManager接口提供了操纵数据库的各种方法,如:
(1) persist()方法:把Java对象保存到数据库中。等价于Session接口的persist()方法。
(2) merge()方法:保存或更新数据库中的Java对象。等价于Session接口的merge()方法。
(3) remove()方法:把特定的Java对象从数据库中删除。类似于Session接口的delete()方法。EntityManager接口的remove()方法只能删除持久化状态的对象,而Session接口的delete()方法可以删除持久化状态或游离状态的对象。。
(4) find()方法:从数据库中加载Java对象。等价于Session接口的get()方法。

下面这个BusinessService类通过JPA API来访问数据库:
package mypack;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.io.*;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;

public class BusinessService{

  public static EntityManagerFactory entityManagerFactory;
  
  /** 初始化JPA,创建EntityManagerFactory实例 */
  static{
    try{
      entityManagerFactory=
           Persistence.createEntityManagerFactory( "myunit" );
    }catch(Exception e){
      e.printStackTrace();
      throw e;
    }
  }
  
  /** 查询所有的Customer对象,
      然后调用printCustomer()方法打印Customer对象信息 */

  public void findAllCustomers(PrintWriter out)throws Exception{
    EntityManager entityManager =
           entityManagerFactory.createEntityManager();
    EntityTransaction tx = null;
    try {
      tx = entityManager.getTransaction();
      tx.begin(); //开始一个事务
      Query query=entityManager.createQuery(
           "from Customer as c order by c.name asc");
      List customers=query.getResultList();
      for (Iterator it = customers.iterator(); it.hasNext();) {
         printCustomer(out,(Customer) it.next());
      }

      tx.commit(); //提交事务

    }catch (RuntimeException e) {
      if (tx != null) {
         tx.rollback();
      }
      throw e;
    } finally {
       entityManager.close();
    }
  }

  /** 持久化一个Customer对象 */
  public void saveCustomer(Customer customer){
    EntityManager entityManager =
            entityManagerFactory.createEntityManager();

    EntityTransaction tx = null;
    try {
      tx = entityManager.getTransaction();
      tx.begin();
      entityManager.persist(customer);
      tx.commit();

    }catch (RuntimeException e) {
      if (tx != null) {
        tx.rollback();
      }
      throw e;
    } finally {
      entityManager.close();
    }
  }

  /** 按照OID加载一个Customer对象,然后修改它的属性 */
  public void loadAndUpdateCustomer(Long customer_id,String address){
    EntityManager entityManager =
                  entityManagerFactory.createEntityManager();
    EntityTransaction tx = null;
    try {
      tx = entityManager.getTransaction();
      tx.begin();
      Customer c=entityManager
                    .find(Customer.class,customer_id);
      c.setAddress(address);
      tx.commit();

    }catch (RuntimeException e) {
      if (tx != null) {
        tx.rollback();
      }
      throw e;
    } finally {
      entityManager.close();
    }
  }

  /**删除Customer对象 */
  public void deleteCustomer(Customer customer){
    EntityManager entityManager =
            entityManagerFactory.createEntityManager();
    EntityTransaction tx = null;
    try {
      tx = entityManager.getTransaction();
      tx.begin();
      //获得持久化状态的Customer对象
      Customer c=entityManager
          .find(Customer.class,customer.getId());
      entityManager.remove(c);
      tx.commit();

    }catch (RuntimeException e) {
      if (tx != null) {
        tx.rollback();
      }
      throw e;
    } finally {
      entityManager.close();
    }
  }
  
  /** 把Customer对象的信息输出到控制台,如DOS 控制台*/
  private void printCustomer(PrintWriter out,Customer customer)
                                      throws Exception{……}

  public void test(PrintWriter out) throws Exception{……}

  public static void main(String args[]) throws Exception{
    new BusinessService2().test(new PrintWriter(System.out,true));
    entityManagerFactory.close();
  }
}

          对JPA的初始化非常简单,只要通过javax.persistence.Persistence的静态方法createEntityManagerFactory()来创建EntityManagerFactory对象:

entityManagerFactory=
  Persistence.createEntityManagerFactory( "myunit" );

          以上Persistence.createEntityManagerFactory( “myunit” )方法中的参数“myunit”指定持久化单元包的名字。JPA会到persistence.xml配置文件中读取相应的持久化单元包中的配置信息。

所有访问数据库的操作都使用以下流程:

EntityManager entityManager =
     entityManagerFactory.createEntityManager();
EntityTransaction tx = null;
try {
  tx = entityManager.getTransaction();
  tx.begin();  //声明开始事务
  //执行查询、保存、更新和删除等各种数据访问操作
  ……
  tx.commit();  //提交事务
}catch (RuntimeException e) {
  if (tx != null)
    tx.rollback();
  throw e;
} finally {
  entityManager.close();
}

          点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小


程序猿的技术大观园:www.javathinker.net





[这个贴子最后由 admin 在 2021-10-09 10:44:02 重新编辑]
  Java面向对象编程-->集合(上)
  JavaWeb开发-->Servlet技术详解(Ⅱ)
  JSP与Hibernate开发-->映射对象标识符
  Java网络编程-->RMI框架
  精通Spring-->Vue组件开发高级技术
  Vue3开发-->绑定表单
  【Vue.js技术专题】分割setup()函数
  【Spring Cloud Alibaba专题】@SentinelResource注解的用法
  【持久化专题】为什么JPA和Hibernate的持久化方法都抛出运行...
  【Spring专题】服务器端推送
  【Spring专题】@ControllerAdvice注解的用法
  【Spring专题】@Query和@Modifying注解的增删改操作
  【Vue专题】Vue3的计算属性实用范例:实现购物车
  【Java网络编程专题】用Java套接字编写基本的客户/服务器程序
  【Java网络编程专题】优化访问数据库的程序代码的一些技巧
  【JavaWeb专题】Spring MVC创建Web应用范例,轻松入门
  【JavaWeb专题】Tomcat与IIS集成详解
  IT技术书写作技巧分享:慎用概念和术语
  《大话Java程序设计从入门到精通》写作花絮
  【Java基础编程专题】Java基本类型和引用类型的三个区别
  我的计算机书籍创作心得
  更多...
 IPIP: 已设置保密
楼主      
1页 0条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。