1 JPA入门----项目搭建以及CRUD

Posted 大佛拈花-GoSaint

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1 JPA入门----项目搭建以及CRUD相关的知识,希望对你有一定的参考价值。

maven搭建JPA开发环境
1 依赖的maven pom文件
    主要有hibernate-core、hibernate-entitymanager、javax-persistence、mysql驱动
<?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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>jap-xx</artifactId>
        <groupId>com.cmos</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>jpa-01</artifactId>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <hibernate.version>4.3.8.Final</hibernate.version>
        <junit.version>4.12</junit.version>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--hibernate-core-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- hibernate-entitymanager-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!--javax.persistence-->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
    </dependencies>
</project>
2 配置persistence.xml文件
    在资源文件夹下创建META-INF文件夹,创建persistence.xml文件
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistencehttp://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="com.cmos.jpa" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql:///jpa"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="gosaint"/>
            <!--mysql方言-->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <!--显示sql-->
            <property name="hibernate.show_sql" value="true"/>
            <!--自动建表-->
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <!--格式化sql-->
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>
3 创建实体类Employee类。
    新建数据库,名为jpa,配置好上述的persistence.xml文件;新建实体类Employee
package com.cmos.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column
    private String name;
    private String password;
    ...
    省略getter()和setter()
}

4 新建测试类EmployeeTest

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

import com.cmos.jpa.Employee;

import org.junit.Test;

public class EmployeeTest {
    
    @Test
    public void save() throws Exception {
        Employee employee=new Employee();
        employee.setName("张三");
        employee.setPassword("123456");
        String persistenceUnitName="com.cmos.jpa";
        // 1 获取实例管理工厂
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
        // 2 获取实例管理对象
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        // JAP默认事务不开启
        EntityTransaction transaction = entityManager.getTransaction();
        //3 开启事务
        transaction.begin();
        //4 持久化操作
        entityManager.persist(employee);
        //5 提交事务
    transaction.commit();
        //6 关闭资源
        entityManager.close();
        entityManagerFactory.close();

    }
}
如下的结果显示:
查看数据库,发现存在测试数据!
5 注解解释
上述的注解解释:
① @Entity:表示实体对象,这个对象和数据库的表建立对应关系
② @Table(name="表名") 如果没有配置该注解或者该注解使用默认值关系,那么表的名称为类名称,首字母小写
③ @Id 表示主键
④ @GeneratedValue 配置主键的生成策略,默认值是@GeneratedValue(strategy = GenerationType.AUTO)
 主键策略如果是:strategy = GenerationType.AUTO  在Mysql中就是:主键:AUTO_INCREMENT,在Oracle中就是序列;
表示主键自动
⑤ @Column注解:加在字段上,如果希望字段的名称和数据库对应的字段不一致,可以使用该注解,并且设置对应的列名;如果希望一致,可以不用加该注解
6 工具类抽取
public class JPAUtils {
    private static EntityManagerFactory entityManagerFactory;
    static {
        try {
            String persistenceUnitName="com.cmos.jpa";
            entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
        }catch (Exception e){
            throw new RuntimeException("配置文件出错"+e.getMessage());
        }

    }
    public static EntityManager getEntity(){
        return entityManagerFactory.createEntityManager();
    }

    public static void close(){
        if(entityManagerFactory!=null){
            entityManagerFactory.close();
        }
    }
}
7 测试CRUD操作
    补充:建表策略是create:表示先删除表,然后建立新的表;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.cmos.jpa.Employee;
import com.cmos.jpa.JPAUtils;

import org.junit.Before;
import org.junit.Test;

/**
* 查询一个: find(T.class,Long id)
* 修改: merge(T)
* 保存:persistence(T)
* 删除:remove(T) 直接删除对象
*
*/
public class EmployeeTest2 {
    /**
     * 保存
     */
    @Before
    public void save(){
        Employee employee=new Employee();
        employee.setName("张三");
        employee.setPassword("123456");
        Employee employee2=new Employee();
        employee2.setName("里斯");
        employee2.setPassword("123456");
        EntityManager entity = JPAUtils.getEntity();
        EntityTransaction transaction = entity.getTransaction();//获取事务
        transaction.begin();
        entity.persist(employee);
        transaction.commit();
    }
    @Test
    public void queryAndUpdate(){
        EntityManager entity = JPAUtils.getEntity();
        entity.getTransaction().begin();
        //查询
        Employee employee = entity.find(Employee.class, 1L);
        System.out.println(employee);
        employee.setName("xyz");
        employee.setPassword("99999");
        //修改
        entity.merge(employee);
        System.out.println(employee);
        entity.getTransaction().commit();
    }

    @Test
    public void delete(){
        EntityManager entity = JPAUtils.getEntity();
        entity.getTransaction().begin();
        Employee employee = entity.find(Employee.class, 1L);
        entity.remove(employee);
        System.out.println(employee);
        entity.getTransaction().commit();
    }
   
    //JPQL查询
    @Test
    public void queryJPQL(){
        EntityManager entity = JPAUtils.getEntity();
        entity.getTransaction().begin();
        String jpql="select o from Employee o";
        Query query = entity.createQuery(jpql);
        List<Employee> resultList = query.getResultList();
        for (Employee e:resultList) {
            System.out.println("0000000000");
            System.out.println(e);
        }
        entity.getTransaction().commit();
        
    }


}
7 配置自动建表
create-drop:删除表----建表----删除表(一般不用)
 删除表的时间:EntityManageFactory关闭之后
create----删除表----建立表
update----用在项目中
validate----数据库已经存在(项目已经上线)
总结:JPA的CRUD操作:
查询:find或者使用JPQL查询;
保存:persistence
修改:merge
删除: remove
 
 
 
 
 
 
 
 
 
 
 
 

以上是关于1 JPA入门----项目搭建以及CRUD的主要内容,如果未能解决你的问题,请参考以下文章

Spring-data-Jpa项目搭建

JOOQ 入门-- CRUD 语句

JOOQ 入门-- CRUD 语句

spring data jpa

Spring-Data-JPA尝鲜:快速搭建CRUD+分页后台实例

Hibernate笔记7--JPA CRUD