其他分享
首页 > 其他分享> > 12、JPA查询-3种查询方式

12、JPA查询-3种查询方式

作者:互联网

JPA查询

JPA 3中查询方式

  1. JPQL 方式查询,表和列名称都是类和字段名称 @Entity 名称
  2. SQL 传统SQL查询
  3. @NamedNativeQuery 和@NamedQuery 命名查询,最大程度复用JPQL或SQL

主要用到的API如下所示:

EntityManager entityManager = JpaUtil.getEntityManager();
        //1、JPQL 查询
        entityManager.createQuery("JPQL");
        TypedQuery<Student> jpql = entityManager.createQuery("JPQL", Student.class);

        //设置参数
        jpql.setParameter(1,"索引参数 ?1");
        jpql.setParameter("name","命名参数");

        //分页查询
        jpql.setFirstResult(10);
        jpql.setMaxResults(20);

        //查询返回结果
        Student singleResult = jpql.getSingleResult();
        List<Student> resultList = jpql.getResultList();

        //用于Update 或 delete 操作
        int i = jpql.executeUpdate();

        //2、传统SQL查询方式
        entityManager.createNativeQuery("SQL");
        entityManager.createNativeQuery("SQL",Student.class);

        //3、命名查询
        entityManager.createNamedQuery("queryName");
        entityManager.createNamedQuery("queryName",Student.class);

        entityManager.close();

案例数据准备

1、Entity类型定义

@Data
@Entity(name = "student")
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    @Id
    private long id;

    private String name;

    private int age;

    private Date birthday;
     @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2、persistence.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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_2_0.xsd">

    <!--persistence-unit 可配置多个,每个都是一个环境;name指定环境名词 -->
    <persistence-unit name="jpaDev">
        <class>com.hongying.entity.query.Student</class>

        <exclude-unlisted-classes>true</exclude-unlisted-classes>

        <!--指定属性的配置 -->
        <properties>
            <!--配置数据库方言,告诉JPA使用的数据库类型 -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
            <!--JPA的相关配置信息,hibernate配置基本和这些一样,javax.persistence换成hibernate即可 -->
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="1234.com" />

            <!--hibernate打印执行的SQL到控制台-->
            <property name="hibernate.show_sql" value="true" />

            <!--自动输出schema创建DDL语句 -->
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>

</persistence>

3、初始化查询案例数据

@Test
    public void init(){
        int count=300;

        EntityManager entityManager = JpaUtil.getEntityManager();
        entityManager.getTransaction().begin();

        for(int i=0;i<count;i++){
            Student student=new Student(i+1,"jake"+i,i+23,new Date());
            entityManager.persist(student);
        }

        entityManager.getTransaction().commit();
        entityManager.close();
    }

在这里插入图片描述

查询案例

1、JPQL查询

@Test
    public void query1(){
        EntityManager entityManager = JpaUtil.getEntityManager();
        //1、JPQL 查询所有,不能 select *;表名称对应@Entity(name="student")
//        Query query = entityManager.createQuery("select u from student u");
//        List<Student> results = query.getResultList();
//        for(Student s:results){
//            System.out.println("s.getName() = " + s.getName());
//        }

        //2、查询年龄大于20,小于30的。使用索引参数
//        TypedQuery<Student> query1 = entityManager.createQuery("select u from student u where u.age>?1 and u.age<?2", Student.class);
//        query1.setParameter(1,20);
//        query1.setParameter(2,30);
//        List<Student> resultList = query1.getResultList();
//        for(Student s:resultList){
//            System.out.println("s = " + s);
//        }

        //3、模糊查询,名称包含"2"的值;命名参数 :name;排序;分页查询
        TypedQuery<Student> query = entityManager.createQuery(
                "select u from student u where u.name like :name order by u.id desc",
                Student.class);

        query.setParameter("name","%2%");
        query.setFirstResult(5);
        query.setMaxResults(3);

        List<Student> resultList1 = query.getResultList();
        System.out.println("resultList1 = " + resultList1);

        //4、查询部分字段属性,查询结果封装成另外1个类型
        //有时表比较大,页面上不需要所有数据。这里只查询id,name 封装成另外一个对象。主要这个对象JPA必须也要管理才行
        TypedQuery<Student> result = entityManager.createQuery("select new student(u.id,u.name) from student u", Student.class);
        result.setMaxResults(5);
        List<Student> resultList = result.getResultList();
        System.out.println("resultList = " + resultList);

        entityManager.close();
    }

2、SQL查询

    @Test
    public void query2(){
        EntityManager entityManager = JpaUtil.getEntityManager();
        //SQL 查询
        Query nativeQuery = entityManager.createNativeQuery("select * from student where id=?1", Student.class);
        nativeQuery.setParameter(1,5);
        Object singleResult = nativeQuery.getSingleResult();
        System.out.println("singleResult = " + singleResult);


        entityManager.close();
    }

3、命名查询@NamedNativeQuery @NamedQuery

3.1、命名查询 JPQL和SQL定义

package com.hongying.entity.query;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

/**
 * @author zyk
 * @version 1.0.0
 * @ClassName Student
 * @Description TODO
 * @createTime 2021年07月11日 14:21:00
 */
@Data
@Entity(name = "student")
@AllArgsConstructor
@NoArgsConstructor
//命名查询
//1、SQL 命名查询,指定 resultClass 参数时,创建Query时也需要指定类型
@NamedNativeQueries(value = {
        @NamedNativeQuery(name="getStudentById",query = "select * from student u where u.id=:id",resultClass = Student.class)
})
//2、JPQL 命名查询
@NamedQueries(value = {
        @NamedQuery(name="getStudentBigAge",query = "select u from student u where u.age>:age"),
        @NamedQuery(name="getAll",query = "select u from student u")
})
public class Student {

    @Id
    private long id;

    private String name;

    private int age;

    private Date birthday;

    public Student(long id,String name){
        this.id=id;
        this.name=name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

3.2、命名查询案例

 @Test
    public void query3(){
        EntityManager entityManager = JpaUtil.getEntityManager();

        //SQL 命名查询,这里指定查询结果类型,定义SQL那也必须指定resultClass,否则找不到NameQuery报错
        TypedQuery<Student> getStudentById = entityManager.createNamedQuery("getStudentById", Student.class);
        getStudentById.setParameter("id",5);
        Student singleResult = getStudentById.getSingleResult();
        System.out.println("singleResult = " + singleResult);

        //JPQL
        Query getStudentBigAge1 = entityManager.createNamedQuery("getStudentBigAge");
        getStudentBigAge1.setParameter("age",90);
        List getStudentBigAge =getStudentBigAge1.getResultList();
        System.out.println("getStudentBigAge = " + getStudentBigAge);

        entityManager.close();
    }

标签:entityManager,name,JPA,查询,12,Student,SQL,id
来源: https://blog.csdn.net/u011109679/article/details/118654297