首页 > 其他分享 >第二百八十节 JPA教程 - JPA 查询Exists示例

第二百八十节 JPA教程 - JPA 查询Exists示例

时间:2024-10-15 09:46:05浏览次数:8  
标签:return String Exists 示例 JPA void Column import public

JPA教程 - JPA 查询Exists示例

如果子查询返回任何行,则EXISTS条件返回true。

以下代码显示如何在JPQL中使用带有子查询的EXISTS运算符。

    List l = em.createQuery(
        "SELECT e FROM Professor e WHERE EXISTS "
        + "(SELECT p FROM Phone p WHERE p.employee = e)")
        .getResultList();

以下代码显示如何使用NOT EXISTS。

    List l = em.createQuery(
        "SELECT e FROM Professor e WHERE NOT EXISTS (SELECT p FROM e.phones p)")
        .getResultList();

例子

下面的代码来自PersonDaoImpl.java。

package cn.w3cschool.common;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PersonDaoImpl {
  public void test() {
    prepareData();
    
    List l = em.createQuery(
        "SELECT e FROM Professor e WHERE EXISTS "
        + "(SELECT p FROM Phone p WHERE p.employee = e)")
        .getResultList();
    for (Object p : l) {
      printResult(p);
    }
  }

  private void prepareData() {
    Professor p = new Professor();
    p.setId(0);
    p.setName("TOM");
    p.setSalary(1111L);

    Department d = new Department();
    d.setId(1);
    d.setName("Design");

    p.setDepartment(d);
    d.getProfessors().add(p);

    Phone phone = new Phone();
    phone.setId(1);
    phone.setNumber("111-111-1111");
    phone.setProfessor(p);
    
    em.persist(p);
    em.persist(phone);
    em.persist(d);
  }

  private static void printResult(Object result) {
    if (result == null) {
      System.out.print("NULL");
    } else if (result instanceof Object[]) {
      Object[] row = (Object[]) result;
      System.out.print("[");
      for (int i = 0; i < row.length; i++) {
        printResult(row[i]);
      }
      System.out.print("]");
    } else if (result instanceof Long || result instanceof Double
        || result instanceof String) {
      System.out.print(result.getClass().getName() + ": " + result);
    } else {
      System.out.print(result);
    }
    System.out.println();
  }

  @PersistenceContext
  private EntityManager em;
}

下面的代码来自Department.java。

package cn.w3cschool.common;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Department {
    @Id
    private int id;
    private String name;
    @OneToMany(mappedBy="department")
    private Set<Professor> employees = new HashSet<Professor>();

    public int getId() {
        return id;
    }
    
    public void setId(int deptNo) {
        this.id = deptNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String deptName) {
        this.name = deptName;
    }
    
    public Set<Professor> getProfessors() {
        return employees;
    }

    public String toString() {
        return "Department no: " + getId() + 
               ", name: " + getName();
    }
}

以下代码来自Address.java。

package cn.w3cschool.common;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Address {
    @Id
    private int id;
    private String street;
    private String city;
    private String state;
    private String zip;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getStreet() {
        return street;
    }
    
    public void setStreet(String address) {
        this.street = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }
    public String toString() {
        return "Address id: " + getId() + 
               ", street: " + getStreet() +
               ", city: " + getCity() +
               ", state: " + getState() +
               ", zip: " + getZip();
    }

}

以下代码来自Professor.java。

package cn.w3cschool.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Professor {
    @Id
    private int id;
    private String name;
    private long salary;
    @Temporal(TemporalType.DATE)
    private Date startDate;
    
    @OneToOne
    private Address address;
    
    @OneToMany(mappedBy="employee")
    private Collection<Phone> phones = new ArrayList<Phone>();
    
    @ManyToOne
    private Department department;
    
    @ManyToOne
    private Professor manager;
    
    @OneToMany(mappedBy="manager")
    private Collection<Professor> directs = new ArrayList<Professor>();
    
    @ManyToMany(mappedBy="employees")
    private Collection<Project> projects = new ArrayList<Project>();

    public int getId() {
        return id;
    }
    
    public void setId(int empNo) {
        this.id = empNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }

    public long getSalary() {
        return salary;
    }

    public void setSalary(long salary) {
        this.salary = salary;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    
    public Collection<Phone> getPhones() {
        return phones;
    }
    
    public void addPhone(Phone phone) {
        if (!getPhones().contains(phone)) {
            getPhones().add(phone);
            if (phone.getProfessor() != null) {
                phone.getProfessor().getPhones().remove(phone);
            }
            phone.setProfessor(this);
        }
    }
    
    public Department getDepartment() {
        return department;
    }
    
    public void setDepartment(Department department) {
        if (this.department != null) {
            this.department.getProfessors().remove(this);
        }
        this.department = department;
        this.department.getProfessors().add(this);
    }
    
    public Collection<Professor> getDirects() {
        return directs;
    }
    
    public void addDirect(Professor employee) {
        if (!getDirects().contains(employee)) {
            getDirects().add(employee);
            if (employee.getManager() != null) {
                employee.getManager().getDirects().remove(employee);
            }
            employee.setManager(this);
        }
    }
    
    public Professor getManager() {
        return manager;
    }
    
    public void setManager(Professor manager) {
        this.manager = manager;
    }

    public Collection<Project> getProjects() {
        return projects;
    }
    
    public void addProject(Project project) {
        if (!getProjects().contains(project)) {
            getProjects().add(project);
        }
        if (!project.getProfessors().contains(this)) {
            project.getProfessors().add(this);
        }
    }
    
    public Address getAddress() {
        return address;
    }
    
    public void setAddress(Address address) {
        this.address = address; 
    }
    
    public String toString() {
        return "Professor " + getId() + 
               ": name: " + getName() +
               ", salary: " + getSalary() +
               ", phones: " + getPhones() +
               ", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
               ", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
    }

}

以下代码来自Project.java。

package cn.w3cschool.common;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.ManyToMany;

@Entity
@Inheritance
public class Project {
    @Id
    protected int id;
    protected String name;
    @ManyToMany
    protected Collection<Professor> employees = new ArrayList<Professor>();
    
    public int getId() {
        return id;
    }
    
    public void setId(int projectNo) {
        this.id = projectNo;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String projectName) {
        this.name = projectName;
    }
    
    public Collection<Professor> getProfessors() {
        return employees;
    }
    
    public void addProfessor(Professor employee) {
        if (!getProfessors().contains(employee)) {
            getProfessors().add(employee);
        }
        if (!employee.getProjects().contains(this)) {
            employee.getProjects().add(this);
        }
    }
    
    public String toString() {
        return getClass().getName().substring(getClass().getName().lastIndexOf(".")+1) + 
                " no: " + getId() + 
                ", name: " + getName();
    }
}

以下代码来自Phone.java。

package cn.w3cschool.common;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Phone {
    @Id
    private long id;
    private String number;
    private String type;
    @ManyToOne
    Professor employee;
    
    public long getId() {
        return id;
    }
    
    public void setId(long id) {
        this.id = id;
    }
    
    public String getNumber() {
        return number;
    }
    
    public void setNumber(String phoneNo) {
        this.number = phoneNo;
    }
    
    public String getType() {
        return type;
    }
    
    public void setType(String phoneType) {
        this.type = phoneType;
    }
    
    public Professor getProfessor() {
        return employee;
    }

    public void setProfessor(Professor employee) {
        this.employee = employee;
    }

    public String toString() {
        return "Phone id: " + getId() + 
               ", no: " + getNumber() +
               ", type: " + getType();
    }
}

以下是数据库转储。

Table Name: ADDRESS




Table Name: DEPARTMENT
 Row:
    Column Name: ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: Design





Table Name: PHONE
 Row:
    Column Name: ID,
    Column Type: BIGINT:
    Column Value: 1

    Column Name: NUMBER,
    Column Type: VARCHAR:
    Column Value: 111-111-1111

    Column Name: TYPE,
    Column Type: VARCHAR:
    Column Value: null

    Column Name: EMPLOYEE_ID,
    Column Type: INTEGER:
    Column Value: 0





Table Name: PROFESSOR
 Row:
    Column Name: ID,
    Column Type: INTEGER:
    Column Value: 0

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: TOM

    Column Name: SALARY,
    Column Type: BIGINT:
    Column Value: 1111

    Column Name: STARTDATE,
    Column Type: DATE:
    Column Value: null

    Column Name: ADDRESS_ID,
    Column Type: INTEGER:
    Column Value: null

    Column Name: DEPARTMENT_ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: MANAGER_ID,
    Column Type: INTEGER:
    Column Value: null





Table Name: PROJECT




Table Name: PROJECT_PROFESSOR

标签:return,String,Exists,示例,JPA,void,Column,import,public
From: https://blog.csdn.net/2301_78772942/article/details/142936169

相关文章

  • Apache Kafka 使用示例
    Kafka快速入门指南微信公众号:阿俊的学习记录空间小红书:ArnoZhangwordpress:arnozhang1994博客园:arnozhangCSDN:ArnoZhang1994第一步:获取Kafka下载2.13-3.8.0版本的Kafka版本并解压:$tar-xzfkafka_2.13-3.8.0.tgz$cdkafka_2.13-3.8.0第二步:启动Kafka环境注意:你的......
  • <<迷雾>> 第11章 全自动加法计算机(6)--一只开关取数 示例电路
    用一只开关依次将数取出info::操作说明刚启动时,t0=1,t1=t2=0,此时只有IAR`=1.按下开关K不要松开,地址寄存器AR收到一个上升沿信号,保存住当前地址,并提供给存储器(注:第一个地址为0,所以电路中暂看不出什么变化)松开开关K,循环移位计数器RR得到......
  • 【vue文件上传+示例代码】【for循环展示el-teble表格】
    <template><el-rowjustify="space-between"><inputtype="file"id="fileInput"/><el-buttontype="success"@click="doSumbitFile">上传</el-button></el-row>&......
  • ab压测的选项、示例和主要关注的指标意义以及ab压测问题Connection reset by peer (10
    一、ab压测的选项、示例和主要关注的指标意义1.ab压测的一些选项-nrequests    全部请求数-cconcurrency 并发数-ttimelimit   最传等待回应时间-ppostfile    POST数据文件-Tcontent-typePOSTContent-type-vverbosity   Howmuchtroubl......
  • 生产者消费者c++ 讲解和代码示例
    生产者-消费者问题的C++讲解和代码示例一、问题描述生产者-消费者问题是经典的多线程同步问题,涉及两个类型的线程:生产者线程:负责生成数据并放入共享缓冲区。消费者线程:负责从共享缓冲区取出数据进行处理。关键挑战在于:同步:确保生产者和消费者在访问共享缓冲区时不发生......
  • C#通用文档API接口集成示例-合同识别-智能文档识别
    在数字化转型的时代,企业面临着海量的文档数据,这些数据的处理不仅影响工作效率,还对企业的业务决策产生重要影响。然而,手工处理和管理这些文档,不仅效率低下,还可能因为人为错误导致数据的丢失或处理延误。面对这种挑战,智能文档识别技术成为解决企业文档管理难题的关键利器。......
  • <<迷雾>> 第11章 全自动加法计算机(1)--比特单元 示例电路
    具有唯一输入/输出线的存储器info::操作说明读取时,将读R开关闭合即可,Q的输出将通过传输门G到达输出DB处写入时,首先将写W开关闭合,再将上方为测试引入的开关闭合,此时此高电平将写入Q之后断开写W的开关,写入状态结束,之后可将上方为测试引入的开......
  • echarts使用【示例】
    下载npminstallecharts示例<template><divid="main"style="width:600px;height:400px;"></div></template><scriptsetup>import{onMounted}from'vue';import*asechartsfrom'echart......
  • SUI Move官方示例合约实践——FT类:篮子代币(basket)
    SUIMove官方示例合约实践——FT类:篮子代币(basket)1合约说明1.1功能介绍本合约是一个由一篮子代币合成的同质化代币合约,本示例中一篮子代币是由SUI和MANAGED代币1:1组成,但这种方法适用于创建任意资产和比例的篮子。提供了2个写入接口mint:铸造篮子代币,通过存入特定比例......
  • 使用echarts报错【echarts使用示例】
    错误代码<template><h1>home</h1><divid="main"style="width:600px;height:400px;"></div></template><scriptsetup>import{onMounted}from'vue';import*asechartsfrom'ec......