JPA JPQL

本文介绍了JPA中的JPQL语言,一种与SQL类似的用于对象查询的语言,用于屏蔽不同数据库之间的差异。文章详细讲解了JPQL的使用,包括创建Query对象的三种方式:createNamedQuery、createQuery和createNativeQuery,并通过实例展示了如何进行查询、更新和删除操作。同时,文章还涉及到了实体类的定义和缓存的使用,并提供了增删改查的示例代码。
摘要由CSDN通过智能技术生成

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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值