JPA 与 JDBC 的区别和基本用法

JPA 概念

JPA(Java Persistence API)用于对象持久化的 API,是 Java EE 5.0 平台标准的 ORM 规范,使得应用程序以统一的方式访问持久层。

与 JDBC 的对比

JDBC 也是一种规范和接口,不过 JDBC 是面向 SQL 的,使用起来比较繁琐。所以就有了 ORM 框架,建立了 Java 对象与数据库表之间的映射关系,可以通过直接操作对象来实现持久化,简化了操作的繁杂度。而 JPA 就是 ORM 框架的规范,值得一提的是 Hibernate 是符合 JPA 规范的,而 MyBatis 却不符合,因为 MyBatis 还是需要写 SQL 的。

JDBC 示意图:


JPA 示意图:


例子

在 IDEA 下创建一个 JPA 项目,并实现基本的 CRUD。

1、创建一个 JavaEE Persistence 项目,具体如下所示


采用 Hibernate 实现 JPA。

2、导入相应的 Maven 依赖


添加 Maven 支持。

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>jpa-helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

   <dependencies>
       <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
       <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate-entitymanager</artifactId>
           <version>5.4.0.Final</version>
       </dependency>

       <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.11</version>
       </dependency>

   </dependencies>
</project>

3、配置数据库(MySQL 8)相关内容 persistence.xml

注意此文件要位于类路径下,这里放在 resources/META-INF 下。

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">

    <persistence-unit name="jpa-1">
        <!--是 PersistenceProvider 接口的实现类-->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <!--添加持久化类-->
        <class>com.yunche.helloworld.Customer</class>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpa?useSSL=false&amp;serverTimezone=Asia/Shanghai"/>
            <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="123456"/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <!--注意这个属性,自动生成的文件前面没有 hibernate,要加上 hibernate -->
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <!-- 使用 MySQL8Dialect -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>

        </properties>
    </persistence-unit>
</persistence>

4、新建一个持久化对象类

package com.yunche.helloworld;

import javax.persistence.*;

/**
 * @ClassName: Customer
 * @Description:
 * @author: yunche
 * @date: 2019/01/16
 */
@Entity(name = "customers")
public class Customer {

    private Integer age;
    private String lastName;
    private Integer id;
    private String email;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Column(name = "last_name")
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

并在 persistence.xml 中的 persistence-unit 节点下加入:

<!--添加持久化类-->
<!--后来发现:似乎可以不加-->
<class>com.yunche.helloworld.Customer</class>

5、Main 类

package com.yunche.helloworld;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 * @ClassName: Main
 * @Description:
 * @author: yunche
 * @date: 2019/01/16
 */
public class Main {
    public static void main(String[] args) {

        //persistence.xml 中的 persistence-unit
        String persistenceUnitName = "jpa-1";
        //1、创建 EntityManagerFactory
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
        //2、创建 EntityManager
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        //3、开启事务
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        //4、进行持久化操作
        Customer customer = new Customer();
        customer.setAge(13);
        customer.setLastName("li");
        customer.setEmail("123@qq.com");

        entityManager.persist(customer);
        //5、提交事务
        transaction.commit();
        //6、关闭 EntityManager
        entityManager.close();
        //7、关闭 EntityManagerFactory
        entityManagerFactory.close();
    }
}

6、结果



7、注意事项
我后来发现了一点问题,关于包 javax.persistence-api 的,我创建项目的时候选中了 persistence 2.0 , IDEA 自动导入了 javax.persistence-api-2.0.jar,而 maven 下的 hibernate-entitymanager 依赖含有 javax.persistence-api-2.2.jar ,所以 jar 包重复了,并且我发现2.0版本的有些方法没有,所以还是将2.0版本的jar包删除,用 2.2 版本的。

参考资料

尚硅谷 佟刚 JPA。

posted @ 2019-01-16 20:51  云--澈  阅读(11856)  评论(0编辑  收藏  举报