首页 > 其他分享 >第二百六十节 JPA教程 - JPA查询命名参数示例

第二百六十节 JPA教程 - JPA查询命名参数示例

时间:2024-10-02 19:49:21浏览次数:11  
标签:return String 示例 JPA void 二百六十 Column import public

JPA教程 - JPA查询命名参数示例

JPQL支持两种类型的参数绑定语法。

第一种是位置绑定,其中参数在查询字符串中通过问号后面跟随参数号来指示。

执行查询时,开发人员指定应替换的参数编号。

SELECT e
FROM Employee e
WHERE e.department = ?1 AND
      e.salary > ?2

命名参数在查询字符串中用冒号后跟参数名称指示。

当执行查询时,开发人员指定应该替换的参数名称。

这种类型的参数允许更具描述性的参数说明符。

SELECT e
FROM Employee e
WHERE e.department = :dept AND
      e.salary > :base

以下代码显示如何使用命名参数。

    List l = em.createQuery(    "SELECT e " +
        "FROM Professor e " +
        "WHERE e.department = :dept AND " +
        "      e.salary = (SELECT MAX(e2.salary) " +
        "                  FROM Professor e2 " +
        "                  WHERE e2.department = :dept)")
        .setParameter("dept", d)
        .getResultList();

例子

以下代码来自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();
    }

}

下面的代码来自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();
    
    Department d = new Department();
    d.setId(1);
    d.setName("Design");
    
    List l = em.createQuery(    "SELECT e " +
        "FROM Professor e " +
        "WHERE e.department = :dept AND " +
        "      e.salary = (SELECT MAX(e2.salary) " +
        "                  FROM Professor e2 " +
        "                  WHERE e2.department = :dept)")
        .setParameter("dept", d)
        .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);

    em.persist(p);
    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();
    }
}

以下代码来自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();
    }
}

以下代码来自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());
    }

}

上面的代码生成以下结果。

以下是数据库转储。

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




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,示例,JPA,void,二百六十,Column,import,public
From: https://blog.csdn.net/2301_78772942/article/details/142664942

相关文章

  • 鸿蒙应用示例:键盘管理从避免遮挡到显示监听的方案实践
    在HarmonyOS应用开发中,键盘管理是一个关键环节,直接影响着用户体验。本文将探讨HarmonyOS键盘管理的几个重要方面,包括如何避免软键盘遮挡输入框、键盘显示与隐藏的监听机制,以及如何手动控制键盘的显示与隐藏。一、避免软键盘遮挡输入框在默认情况下,当用户在输入框中输入文本时,软键盘......
  • <<迷雾>> 第5章 从逻辑学到逻辑电路(4)--或门及其符号 示例电路
    info::操作说明鼠标单击开关切换开合状态系统中使用一个类似箭头的形状表示或门primary::在线交互操作链接https://cc.xiaogd.net/?startCircuitLink=https://book.xiaogd.net/cyjsjdmw-examples/assets/circuit/cyjsjdmw-ch05-13-or-gate.txt原图......
  • C++在游戏开发中的卓越性能:优势解析与代码示例
    在游戏开发领域,C++一直是一种备受青睐的编程语言。它以其高性能、灵活性和强大的功能集,成为了游戏开发者的首选语言之一。在本文中,我们将深入探讨C++在游戏开发中的优势,并提供一些代码示例来展示这些优势是如何在实际开发中发挥作用的。高性能与低级控制C++提供接近硬件......
  • 八字测算api接口数据示例_奥顺八字测算接口分享
    八字测算免费api接口,每日开放时间在早上8点到晚上十点,本api接口完全免费,是奥顺居八字测算网程序内部接口,提供本地调用的,现在免费分享出来,仅供测试。接口名称:八字精批测算api接口示例接口平台:奥顺居八字测算程序内部接口接口格式:JSON请求方式:HTTPSGET请求示例https://blog.w......
  • C#通用文档识别挂接示例、手写体识别接口
    通用文档识别服务接口支持扫描文档、长微博、自然场景下的各种印刷体文字、手写体文字、繁体文字、英文、阿拉伯文等文字的识别,提供免费测试与在线体验服务部署方式灵活多样,支持标准化HTTP、WebService接口集成,支持私有化部署,支持CPU、GPU以及国产化操作系统部署,支持返回......
  • <<迷雾>> 第5章 从逻辑学到逻辑电路(2)--非门 示例电路
    一个应用非门的例子info::操作说明鼠标单击开关切换开合状态primary::在线交互操作链接https://cc.xiaogd.net/?startCircuitLink=https://book.xiaogd.net/cyjsjdmw-examples/assets/circuit/cyjsjdmw-ch05-05-not-gate-sample.txt原图一个自带电源的常闭触点......
  • LightDB rownum使用示例及性能测试
    如下所示:lightdb@oradb=#explainanalyzeselect*from(selecta.*,rownumrnfrom(select*fromv,v1wherev.id=v1.idandnotexists(select1fromtwhereid<>v.id)andv1.id<>'31'orderbyv1.id)awhererownum<100000+1000)whe......
  • 【Go语言基础——一个Go语言项目典型的文件结构示例】
    1.在一个Go语言项目中,文件结构通常遵循一定的约定和最佳实践。以下是一个典型的Go项目结构示例,以及每个部分的说明:my-go-project/├──cmd/│├──myapp/││└──main.go#主程序入口├──internal/│├──pkg1/#......
  • 优化 Windows 触控笔的设置,你可以创建一个 .reg 文件来修改注册表。下面是一个示例内
    优化Windows触控笔的设置,你可以创建一个.reg文件来修改注册表。下面是一个示例内容,你可以根据需要进行调整:打开记事本或任何文本编辑器。将以下内容复制并粘贴到文件中:CopyCodeWindowsRegistryEditorVersion5.00;优化触控笔设置[HKEY_CURRENT_USER\Software\Mi......
  • <<迷雾>> 第 3 章 怎样才能让机器做加法 示例电路
    全加器示意图info::操作说明鼠标单击开关切换开合状态primary::在线交互操作链接https://cc.xiaogd.net/?startCircuitLink=https://book.xiaogd.net/cyjsjdmw-examples/assets/circuit/cyjsjdmw-ch03-01-full-adder.txt原图由3个全加器组成的3比特加法机info......