JPA JPQL

JPA JPQL

一、JPA简介

JPQL语言,即 Java Persistence Query Language 的简称。JPQL 是一种和 SQL 非常类似的中间性和对象化查询语言,它最终会被编译成针对不同底层数据库的 SQL 查询,从而屏蔽不同数据库的差异。如果会hibernate的hql查询,那么jpql会上手的很快。
JPQL语言的语句可以是 select 语句、update 语句或delete语句,它们都通过 Query 接口封装执行。
Query接口封装了执行数据库查询的相关方法。调用 EntityManager 的 createQuery、create NamedQuery 及 createNativeQuery 方法可以获得查询对象,进而可调用 Query 接口的相关方法来执行查询操作。

二、实体类

user类

package com.kuang.pojo;

import org.hibernate.annotations.Generated;

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

@NamedQuery(name = "namedUser",query = "from User where id>?")
@Cacheable(true)
@Table(name = "User_01")
@Entity
public class User {
    private int id;
    private String name;
    private int age;
    private Date Birth;
    private boolean sex;

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

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public Date getBirth() {
        return Birth;
    }

    @Temporal(value = TemporalType.DATE )
    public void setBirth(Date birth) {
        Birth = birth;
    }


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

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }
}

学生类

package com.kuang.pojo;

import javax.persistence.*;

@Entity
@Table(name = "JPA_STUDENT")
public class Student {
    private Integer id;
    private String lastName;
    private Boolean sex;
    private Integer age;
    private Teacher teacher;


    @JoinColumn(name = "TEACHER_ID")
    @ManyToOne(fetch = FetchType.LAZY)
    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Id
    @GeneratedValue
    public Integer getId() {
        return id;
    }

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

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

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

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

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

二、JPQL的三种查询

1、createNamedQuery

根据实体类@NamedQuery(name = “namedUser”,query = “from User where id>?”)

2、createQuery

创建Query, 可以根据对象查询sql

3、createNativeQuery

根据本地sql 查询

测试

package com.kuang.test;

import com.kuang.pojo.Student;
import com.kuang.pojo.User;
import org.hibernate.ejb.QueryHints;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class TestJPQL {

    private EntityManagerFactory entityManagerFactory;
    private EntityManager entityManager;
    private EntityTransaction transaction;

    @Before
    public void init(){
        entityManagerFactory= Persistence.createEntityManagerFactory("jpaHello");
        entityManager = entityManagerFactory.createEntityManager();
        transaction= entityManager.getTransaction();
        transaction.begin();
    }

    @After
    public void destroy(){
        transaction.commit();
        entityManager.close();
        entityManagerFactory.close();
    }

    @Test
    public void testJPQL(){
        // sql语句
        String sql="from User";
        // 创建Query对象
        Query query = entityManager.createQuery(sql);
        // 
        List<User> resultList = query.getResultList();

        for (User user : resultList) {
            System.out.println(user.getName());
        }

    }

    @Test
    public void testJPQL01(){
        String sql="from User where id=?";
        Query query = entityManager.createQuery(sql);
        query.setParameter(1,1);
        User user = (User) query.getSingleResult();

        System.out.println(user.getName());
    }

    @Test
    public void testJQOLNamed(){
        Query query = entityManager.createNamedQuery("namedUser");
        query.setParameter(1, 0);
        List<User> list = query.getResultList();

        for (User user : list) {
            System.out.println(user.getName());
        }
    }

    @Test
    public void testJQOlNative(){
        String jpql="select * from user_01";
        Query query = entityManager.createNativeQuery(jpql);
        List list = query.getResultList();
        for (Object o : list) {
            System.out.println(o);
        }
    }

    @Test
    public void testCache(){
        Query query = entityManager.createNamedQuery("namedUser").setHint(QueryHints.HINT_CACHEABLE,true);
        query.setParameter(1, 0);
        List<User> list = query.getResultList();

        for (User user : list) {
            System.out.println(user.getName());
        }

        query = entityManager.createNamedQuery("namedUser").setHint(QueryHints.HINT_CACHEABLE,true);
        query.setParameter(1, 0);
        list = query.getResultList();
        System.out.println(list.size());
    }

    @Test
    public void leftTest(){
        String sql="from Student stu left outer join fetch stu.teacher  where stu.id =?";
        Query query = entityManager.createQuery(sql);
        query.setParameter(1,1);

        List<Student> list = query.getResultList();

        for (Student student : list) {
            System.out.println(student.getLastName());
            System.out.println(student.getTeacher().getName());
        }
    }

    @Test
    public void fucntionTest(){
        String sql=" from Student stu left outer join fetch stu.teacher  where stu.id =?";
        Query query = entityManager.createQuery(sql);
        query.setParameter(1,1);

        List<Student> list = query.getResultList();

        for (Student student : list) {
            System.out.println(student.getLastName());
            System.out.println(student.getTeacher().getName());
        }
    }

    @Test
    public void testRemove(){
        String jpql="update Student stu set stu.lastName =? where stu.id =? ";
        Query query = entityManager.createQuery(jpql);
        query.setParameter(1,"HaHA");
        query.setParameter(2,1);
        query.executeUpdate();
    }
}

四、增删改

query 对象的增删改可以通过executeUpdate来进行

  @Test
    public void testRemove(){
        String jpql="update Student stu set stu.lastName =? where stu.id =? ";
        Query query = entityManager.createQuery(jpql);
        query.setParameter(1,"HaHA");
        query.setParameter(2,1);
        query.executeUpdate();
    }

你可能感兴趣的:(学习记录,hibernate,sql,jpa)