JPA学习笔记(一)——JPA 入门

1. JPA 和 Hibernate 的关系

JPA 是规范,Hibernate 是实现。从功能上来说,JPA 是 Hibernate 功能的一个子集。

2. 依赖的 jar 包(Hibernate 以 5.4.10 版本为例)

  1. hibernate-release-5.4.10.Final\lib\required*.jar
  2. hibernate-release-5.4.10.Final\lib\jpa-metamodel-generator\hibernate-jpamodelgen-5.4.10.Final.jar
  3. 数据库驱动的 jar 包

3. persistence.xml

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

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="jpa-1" transaction-type="RESOURCE_LOCAL">
        <!-- 
            配置使用什么 ORM 产品来作为 JPA 的实现 
            1. 实际上配置的是 javax.persistence.spi.PersistenceProvider 接口的实现类
            2. 若 JPA 项目中只有一个 JPA 的实现产品, 则也可以不配置该节点. 
		-->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <!-- 添加持久化类 -->
        <class>jpa.helloworld.Customer</class>
        
        <properties>
            <!-- 连接数据库的基本信息 -->
            <property name="hibernate.connection.url" value="jdbc:mysql:///jpa?serverTimezone=UTC"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="1234"/>

            <!-- 配置 JPA 实现产品的基本属性. 即配置 hibernate 的基本属性 -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

4. 对实体类进行持久化操作

// 1. 创建 EntityManagerFactory
String persistenceUnitName = "jpa-1"; // 对应 persistence.xml 的 <persistence-unit name="jpa-1">
EntityManagerFactory entityManagerFactory = 
Persistence.createEntityManagerFactory(persistenceUnitName);
// 2. 创建 EntityManager. 类似于 Hibernate 的 SessionFactory
EntityManager entityManager = entityManagerFactory.createEntityManager();
// 3. 开启事务
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
// 4. 进行持久化操作
Customer customer = new Customer();
customer.setAge(19);
customer.setEmail("惟愿此间无白头@163.com");
customer.setLastName("惟愿此间无白头");
customer.setCreatedTime(new Date());
customer.setBirth(new Date());
entityManager.persist(customer);
// 5. 提交事务
transaction.commit();
// 6. 关闭 EntityManager
entityManager.close();
// 7. 关闭 EntityManagerFactory
entityManagerFactory.close();
发布了5 篇原创文章 · 获赞 8 · 访问量 204

猜你喜欢

转载自blog.csdn.net/DeepClouds/article/details/105621633