举报投诉联系我们 手机版 热门标签 编程学
您的位置:编程学 > jpa 查询 JPA 查询简介示例

jpa 查询 JPA 查询简介示例

2023-03-07 06:18 Java教程

jpa 查询 JPA 查询简介示例

jpa 查询

JPA 查询是 Java 持久化 API(Java Persistence API)的一部分,它提供了一种简单的方法来查询数据库中的数据。JPA 查询使用 Java Persistence Query Language (JPQL) 来定义和执行查询。JPQL 是一种面向对象的 SQL,它允许你使用对象和属性而不是表和字段来定义查询。

JPA 提供了两种方式来执行 JPQL 查询:静态和动态。静态 JPQL 查询是在代码中写死的 JPQL 语句,而动态 JPQL 查询则是在运行时动态生成 JPQL 语句。

JPA 还支持原生 SQL 查询(Native Query)。原生 SQL 是使用标准 SQL 语句来执行数据库操作的方法。原生 SQL 具有很大的灵活性,但是也会带来一些问题:如数据库特定的 SQL 语法、SQL 的可维护性问题以及处理复杂的关联关系问题。

// 静态 JPQL 例子 
String jpql = "SELECT e FROM Employee e WHERE e.salary > :salary"; 
Query query = entityManager.createQuery(jpql); 
query.setParameter("salary", 1000); 
List<Employee> employees = query.getResultList(); 

JPA 查询简介示例

JPA教程 - JPA查询简介示例


最简单的JPQL查询选择单个实体类型的所有实例。

考虑下面的查询:

SELECT e
FROM Employee e

JPQL尽可能使用SQL语法。

SQL查询从表中选择。JPQL从应用程序域模型的实体中选择。

语法

选择查询的整体形式如下:

SELECT <select_expression>
FROM <from_clause>
[WHERE <conditional_expression>]
[ORDER BY <order_by_clause>]

例子

下面的代码来自PersonDaoImpl.java。

package cn..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<Professor> l = em.createQuery("SELECT e FROM Professor e").getResultList();
    for(Professor p:l){
      System.out.println(p);
    }
  }
  
  private void prepareData(){
    Professor p = new Professor();
    p.setId(0);
    p.setName("TOM");
    
    em.persist(p);
  }
  @PersistenceContext
  private EntityManager em;
}

以下代码来自Professor.java。

package cn..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());
    }

}
下载 Query_Simple.zip

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

以下是数据库转储。

Table Name: ADDRESS




Table Name: DEPARTMENT




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: 0

    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: null

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





Table Name: PROJECT




Table Name: PROJECT_PROFESSOR


阅读全文
以上是编程学为你收集整理的jpa 查询 JPA 查询简介示例全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 编程学 bianchengxue.com 版权所有 联系我们
桂ICP备19012293号-7 返回底部