JPA和hibernate

1.JPA的概念一级它和hibernate之间的关系

  JPA:它是java persistence api , java持久化ORM规范,hibernate实现了JAP规范。

2.JPA的环境搭建和入门案例

1.配置pom文件

    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- 添加Hibernate依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.10.Final</version>
        </dependency>

        <!-- 添加Log4J依赖 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.6.4</version>
        </dependency>

        <!-- 添加javassist -->
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.12.0.GA</version>
        </dependency>

        <!-- mysql数据库的驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- 配置hibernate的c3p0数据库连接池 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>5.4.10.Final</version>
        </dependency>

        <!--实现JPA-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.8.Final</version>
        </dependency>

    </dependencies>

2.配置persistence.md.xml主文件

  需要注意的是加载文件的时候,会在类文件下的META-INF下面自动找。test01_hibernate03_jpa\src\main\resources\META-INF\persistence.xml

<?xml version="1.0" encoding="UTF-8" ?>
<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/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

    <!--配置持久化单元(persistence-unit),可以配置多个,名称不能重复
        transaction-type:指定事务类型
            JTA:java Transaction API 规范
            RESOURCE_LOCAL:值本地的代码事务(一般都用这个)
    -->
    <persistence-unit name="myJPAUnit1" transaction-type="RESOURCE_LOCAL">
        <!--JPA规范的提供商 可以不写-->
        <!--<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>-->
       <!-- 指定由JPA注解的实体类位置 可以不写-->
        <!--<class>com.domain.Customer</class>-->
       <!-- 连接数据库配置,用的时hibernate的主配置-->
        <properties>
            <!-- 1.连接数据库的基本信息 -->
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"></property>
            <property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/mybatis"></property>
            <property name="hibernate.connection.username" value="root"></property>
            <property name="hibernate.connection.password" value="root"></property>

            <!-- 2.hibernate的可选配置 -->
            <!-- hibernate里的配置,数据库使用的方言,开发过程中要在控制台显示,sql -->
            <property name="hibernate.show_sql" value="true"></property>
             <property name="hibernate.format_sql" value="true"></property>
            <property name="hibernate.hbm2ddl.auto" value="update"></property>
        </properties>

    </persistence-unit>

</persistence>

3.编写实体类

package com.domain;

import org.hibernate.annotations.Target;

import javax.persistence.*;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * 客户实体类
 * 使用注解时JPA规范,所以导包都需要导入javax.persistence下的包
 */
@Entity  //表明当前类是一个实体类
@Table(name = "jpa_customer")  //建立与数据库表之间的联系
public class Customer implements Serializable {
    @Id //表明当前字段是主键
    @Column(name = "c_id")  //对应数据库中的字段名
    @GeneratedValue(strategy =GenerationType.IDENTITY ) //使用JAP中的主键生成策略
    private Integer id;
    @Column(name = "c_name")
    private String name;
    @Column(name = "c_lovel")
    private String lovel;

}

4.编写工具了,运行,自动生成数据库表

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

public class JPAUtils {
    //类似SessionFactory
    private static EntityManagerFactory factory;

    //加载配置文件
    static {
        factory= Persistence.createEntityManagerFactory("myJPAUnit1");
    }

    public static EntityManager createEntityManager(){
        return factory.createEntityManager();
    }
    //运行数据库表自动生成
    public static void main(String[] args) {
        createEntityManager();
    }
}

5.CRUD测试

import com.domain.Customer;
import com.utils.JPAUtils;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.List;

public class JPATest01 {
    //保存操作 persist()
    @Test
    public void Test01(){
        Customer c=new Customer();
        c.setName("曹操");
        c.setLovel("实诚");
        //1.获取EntityManager
        EntityManager em= JPAUtils.createEntityManager();
        //2.获取事务开启事务
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //3.执行保存操作,persist()方法
        em.persist(c);
        //释放资源
        tx.commit();
        em.close();
    }

    //查询单个实体操作 find()立即加载
    @Test
    public void Test02_1(){
        //1.获取EntityManager
        EntityManager em= JPAUtils.createEntityManager();
        //2.获取事务开启事务
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //3.查询出对象
        Customer customer = em.find(Customer.class, 1);
        System.out.println("===========");
        System.out.println(customer);
        //释放资源
        tx.commit();
        em.close();
    }

    //查询单个实体操作 getReference()延迟加载
    @Test
    public void Test02_2(){
        //1.获取EntityManager
        EntityManager em= JPAUtils.createEntityManager();
        //2.获取事务开启事务
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //3.查询出对象
        Customer customer = em.getReference(Customer.class, 1);
        System.out.println("===========");
        System.out.println(customer);
        //释放资源
        tx.commit();
        em.close();
    }

    //保存merge()用来和并对象保存数据库,以托管状态为主
    @Test
    public void Test03(){
        //1.获取EntityManager
        EntityManager em= JPAUtils.createEntityManager();
        //2.获取事务开启事务
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //3.查询出对象,快照保存
        Customer customer = em.find(Customer.class, 1);
        System.out.println(customer);
        customer.setLovel("黄盖"); //快照保存
        em.merge(customer);
        //释放资源
        tx.commit();
        em.close();
    }

    //删除remove
    @Test
    public void Test04(){
        //1.获取EntityManager
        EntityManager em= JPAUtils.createEntityManager();
        //2.获取事务开启事务
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //3.删除
        Customer customer = em.find(Customer.class, 2);
        em.remove(customer);
        //释放资源
        tx.commit();
        em.close();
    }

    //查询所有
    @Test
    public void Test05(){
        //1.获取EntityManager
        EntityManager em= JPAUtils.createEntityManager();
        //2.获取事务开启事务
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //3.获取Query对象
        //sql不能用*  要用别名
        Query query = em.createQuery("select c from Customer c");
        List list = query.getResultList();
        for (Object o : list) {
            System.out.println((Customer)o);
        }
        //释放资源
        tx.commit();
        em.close();
    }

    //查询所有 有条件
    @Test
    public void Test06(){
        //1.获取EntityManager
        EntityManager em= JPAUtils.createEntityManager();
        //2.获取事务开启事务
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //3.获取Query对象
        //sql 条件要使用‘?1’风格
        Query query = em.createQuery("select c from Customer c where c.name like ?1 and c.lovel = ?2");
        query.setParameter(1,"%曹%");
        query.setParameter(2,"关爱兄弟");
        List list = query.getResultList();
        for (Object o : list) {
            System.out.println((Customer)o);
        }
        //释放资源
        tx.commit();
        em.close();
    }
}

 

 

 

 

  

posted @ 2020-03-08 20:36  Jason–json  阅读(322)  评论(0编辑  收藏  举报