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