JPA使用步骤

来源:互联网 发布:豆瓣短评数据 编辑:程序博客网 时间:2024/05/17 17:59

步骤

  1. 创建 persistence.xml, 在这个文件中配置持久化单元
  2. 需要指定跟哪个数据库进行交互;
  3. 需要指定 JPA 使用哪个持久化的框架以及配置该框架的基本属性
  4. 创建实体类, 使用 annotation 来描述实体类跟数据库表之间的映射关系.
  5. 使用 JPA API 完成数据增加、删除、修改和查询操作
    1. 创建 EntityManagerFactory (对应 Hibernate 中的 SessionFactory);
    2. 创建 EntityManager (对应 Hibernate 中的Session);

persistence.xml

JPA 规范要求在类路径的 META-INF 目录下放置persistence.xml,文件的名称是固定的

详细配置

这里写图片描述

CRUD代码

//创建实体管理者工厂对象        entityManagerFactory=               Persistence.createEntityManagerFactory("jpaTest");        //创建实体管理者        entityManager=entityManagerFactory.createEntityManager();        //创建事务        entityTransaction=entityManager.getTransaction();        //开启事务        entityTransaction.begin();        //进行持久化操作        Student student=new Student(null, "jiayajie", "7989@qq.com", 1);        entityManager.persist(student);        //提交事务        entityTransaction.commit();        //关闭entityManager        entityManager.close();        //关闭entityManagerFactory        entityManagerFactory.close();