阅读 32

【JPA专题】02.JPA入门步骤

JPA入门步骤

**步骤1:**创建一个 JavaEE Persistence 项目(采用 Hibernate 实现 JPA),具体如下所示

Snap4.jpg

Snap2.jpg

**步骤2:**导入相应的 Maven 依赖,选择项目右键,点击Add FrameworkSupport,如图:

Snap5.jpg

**步骤3:**添加Maven的支持,如图:

Snap6.jpg

**步骤4:**添加相关的支持,修改pom.xml,代码如下:

<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>jpa01</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.10.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>

    </dependencies>
</project>
复制代码

**步骤5:**配置JPA的核心配置文件persistence.xml中内容

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

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
             version="2.2">
    <!--
        name属性的名称自己定义
        transaction-type:配置事务管理方式
    -->
    <persistence-unit name="jpa01" transaction-type="RESOURCE_LOCAL">
        <!--
            配置使用什么ORM 产品作为JPA 的实现
            1.实际上配置的是 javax.persistence.spi.PersistenceProvider 接口的实现类
            2.若JPA项目中只有一个JPA的实现产品,则也可以不配置该节点。
        -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <!-- 添加持久化类-->
        <class>com.os.model.Course</class>
        <properties>
            <!-- 配置连接数据库的信息 -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/yf01_mybatis"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value=""/>
            <!-- 或者配置如下
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/yf01_mybatis?useSSL=false&amp;serverTimezone=Asia/Shanghai"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value=""/>
             -->

            <property name="hibernate.id.new_generator_mappings" value="class"/>

            <!-- 配置JPA实现产品的基本属性,配置Hibernate的基本属性 -->
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <!-- 使用 MySQL5Dialect 方言-->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>

        </properties>
    </persistence-unit>
</persistence>
复制代码

**步骤6:**新建持久化类,在这里使用了JPA的相关主键

package com.os.model;

import javax.persistence.*;
import java.util.Date;

@Table(name = "course")//关联的数据表
@Entity//标注为持久化类
public class Course {
    private Integer courseId;
    private String courseName;
    private Date startDate;
    private String location;

    @Id//标注该字段为主键
    @Column(name = "course_id")//设置关联数据表中的字段名
    @GeneratedValue(strategy = GenerationType.IDENTITY)//主键的自增长判断
    public Integer getCourseId() {
        return courseId;
    }

    public void setCourseId(Integer courseId) {
        this.courseId = courseId;
    }

    @Column(name = "course_name",length = 32,nullable = false)
    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
    @Column(name = "start_date")
    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    @Column(length = 128)//默认的name=”location“
    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}
复制代码

**步骤7:**并在 persistence.xml 中的 persistence-unit 节点下加入

<!-- 添加持久化类-->
<class>com.os.model.Course</class>
复制代码

**步骤8:**通过JPA的API步骤完成添加操

public class Test01 {
    public static void main(String[] args) {
        //1.创建EntityManager工厂
        // <persistence-unit name="jpa01" transaction-type="RESOURCE_LOCAL">
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa01");
        //2.获取EntityManager对象
        EntityManager entityManager = factory.createEntityManager();
        //3.开启事务
        EntityTransaction tx = entityManager.getTransaction();
        tx.begin();
        //4.执行操作
        Course course = new Course();
        course.setCourseName("数学");
        course.setLocation("第一教室");
        course.setStartDate(new Date());
        //执行保存操作
        entityManager.persist(course);
        //5.提交事务
        tx.commit();
        //6.关闭EntityManager
        entityManager.close();
        //7.关闭EntityManagerFactory
        factory.close();
    }
}
复制代码

运行主方法后,出现了以下错误:没有找到jpa01的名字

INFO: HHH000318: Could not find any META-INF/persistence.xml file in the classpath
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named jpa01
复制代码

出现该错误的原因是因为persistence.xml的位置没有在classpath下,Maven项目中的classpath指的是resources

Snap7.jpg

修改目录如下

Snap8.jpg

**步骤9:**运行主方法,可能会出现以下错误

Snap9.jpg

修改该问题的描述

<property name="hibernate.hbm2ddl.auto" value="update"/>
修改为:
<property name="hibernate.hbm2ddl.auto" value="create"/>
当表创建完成之后,再将其修改为
<property name="hibernate.hbm2ddl.auto" value="update"/>
复制代码

**步骤10:**结果

Snap10.jpg

附录:项目结构目录

Snap12.jpg

关注下面的标签,发现更多相似文章
评论