JPA 基本查询(一)

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.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<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);}@PersistenceContextprivate EntityManager em;
}

以下代码来自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 {@Idprivate int id;private String name;private long salary;@Temporal(TemporalType.DATE)private Date startDate;@OneToOneprivate Address address;@OneToMany(mappedBy="employee")private Collection<Phone> phones = new ArrayList<Phone>();@ManyToOneprivate Department department;@ManyToOneprivate 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: ADDRESSTable Name: DEPARTMENTTable Name: PHONETable Name: PROFESSORRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: NAME,Column Type: VARCHAR:Column Value: TOMColumn Name: SALARY,Column Type: BIGINT:Column Value: 0Column Name: STARTDATE,Column Type: DATE:Column Value: nullColumn Name: ADDRESS_ID,Column Type: INTEGER:Column Value: nullColumn Name: DEPARTMENT_ID,Column Type: INTEGER:Column Value: nullColumn Name: MANAGER_ID,Column Type: INTEGER:Column Value: nullTable Name: PROJECTTable Name: PROJECT_PROFESSOR

JPA 查询选择两个实体示例

JPA教程 - JPA查询选择两个实体示例

以下JPQL从两个实体中选择。

List l = em.createQuery("SELECT d, m  FROM Department d, Professor m WHERE d = m.department").getResultList();

例子

以下代码来自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 {@Idprivate int id;private String name;private long salary;@Temporal(TemporalType.DATE)private Date startDate;@OneToOneprivate Address address;@OneToMany(mappedBy="employee")private Collection<Phone> phones = new ArrayList<Phone>();@ManyToOneprivate Department department;@ManyToOneprivate 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());}}

以下代码来自Address.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;@Entity
public class Address {@Idprivate 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();List l = em.createQuery("SELECT d, m  FROM Department d, Professor m WHERE d = m.department").getResultList();for(Object p:l){System.out.println(p);}}private void prepareData(){Professor p = new Professor();p.setId(0);p.setName("TOM");Department d = new Department();d.setId(1);d.setName("Design");p.setDepartment(d);d.getProfessors().add(p);em.persist(p);em.persist(d);}@PersistenceContextprivate EntityManager em;
}

以下代码来自Phone.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;@Entity
public class Phone {@Idprivate long id;private String number;private String type;@ManyToOneProfessor 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();}
}

以下代码来自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 {@Idprotected int id;protected String name;@ManyToManyprotected 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();}
}

下面的代码来自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 {@Idprivate 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();}
}

下载 Query_Select_Two_Entities.zip

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

以下是数据库转储。

Table Name: ADDRESSTable Name: DEPARTMENTRow:Column Name: ID,Column Type: INTEGER:Column Value: 1Column Name: NAME,Column Type: VARCHAR:Column Value: DesignTable Name: PHONETable Name: PROFESSORRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: NAME,Column Type: VARCHAR:Column Value: TOMColumn Name: SALARY,Column Type: BIGINT:Column Value: 0Column Name: STARTDATE,Column Type: DATE:Column Value: nullColumn Name: ADDRESS_ID,Column Type: INTEGER:Column Value: nullColumn Name: DEPARTMENT_ID,Column Type: INTEGER:Column Value: 1Column Name: MANAGER_ID,Column Type: INTEGER:Column Value: nullTable Name: PROJECTTable Name: PROJECT_PROFESSOR

JPA 查询选择两个属性示例

JPA教程 - JPA查询选择两个属性示例

从别名开始,我们可以使用点(.)运算符浏览实体关系。

以下JPQL从一个实体中选择两个属性。

    List l = em.createQuery("SELECT e.name, e.salary FROM Professor e")

例子

下面的代码来自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.name, e.salary FROM Professor e").getResultList();for (Object p : l) {printResult(p);}}private void prepareData() {Professor p = new Professor();p.setId(0);p.setName("TOM");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();}@PersistenceContextprivate EntityManager em;
}

以下代码来自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 {@Idprotected int id;protected String name;@ManyToManyprotected 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 {@Idprivate long id;private String number;private String type;@ManyToOneProfessor 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();}
}

以下代码来自Address.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;@Entity
public class Address {@Idprivate 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 {@Idprivate int id;private String name;private long salary;@Temporal(TemporalType.DATE)private Date startDate;@OneToOneprivate Address address;@OneToMany(mappedBy="employee")private Collection<Phone> phones = new ArrayList<Phone>();@ManyToOneprivate Department department;@ManyToOneprivate 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());}}

下面的代码来自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 {@Idprivate 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();}
}

下载 Query_Select_Two_Properties.zip

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

以下是数据库转储。

Table Name: ADDRESSTable Name: DEPARTMENTRow:Column Name: ID,Column Type: INTEGER:Column Value: 1Column Name: NAME,Column Type: VARCHAR:Column Value: DesignTable Name: PHONETable Name: PROFESSORRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: NAME,Column Type: VARCHAR:Column Value: TOMColumn Name: SALARY,Column Type: BIGINT:Column Value: 0Column Name: STARTDATE,Column Type: DATE:Column Value: nullColumn Name: ADDRESS_ID,Column Type: INTEGER:Column Value: nullColumn Name: DEPARTMENT_ID,Column Type: INTEGER:Column Value: 1Column Name: MANAGER_ID,Column Type: INTEGER:Column Value: nullTable Name: PROJECTTable Name: PROJECT_PROFESSOR

JPA 查询命名参数

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

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

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

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

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

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

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

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

SELECT e
FROM Employee e
WHERE e.department = :dept ANDe.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 {@Idprivate 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();}@PersistenceContextprivate 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 {@Idprivate 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 {@Idprotected int id;protected String name;@ManyToManyprotected 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 {@Idprivate long id;private String number;private String type;@ManyToOneProfessor 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 {@Idprivate int id;private String name;private long salary;@Temporal(TemporalType.DATE)private Date startDate;@OneToOneprivate Address address;@OneToMany(mappedBy="employee")private Collection<Phone> phones = new ArrayList<Phone>();@ManyToOneprivate Department department;@ManyToOneprivate 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_Named_Parameter.zip

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

以下是数据库转储。

Table Name: ADDRESSTable Name: DEPARTMENTRow:Column Name: ID,Column Type: INTEGER:Column Value: 1Column Name: NAME,Column Type: VARCHAR:Column Value: DesignTable Name: PHONETable Name: PROFESSORRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: NAME,Column Type: VARCHAR:Column Value: TOMColumn Name: SALARY,Column Type: BIGINT:Column Value: 1111Column Name: STARTDATE,Column Type: DATE:Column Value: nullColumn Name: ADDRESS_ID,Column Type: INTEGER:Column Value: nullColumn Name: DEPARTMENT_ID,Column Type: INTEGER:Column Value: 1Column Name: MANAGER_ID,Column Type: INTEGER:Column Value: nullTable Name: PROJECTTable Name: PROJECT_PROFESSOR

JPA 查询实体参数值示例

JPA教程 - JPA 查询实体参数值示例

以下代码显示如何将实体值作为JPQL的参数传递。

    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();

例子

下面的代码来自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 {@Idprivate 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();}
}

以下代码来自Phone.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;@Entity
public class Phone {@Idprivate long id;private String number;private String type;@ManyToOneProfessor 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();}
}

以下代码来自Address.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;@Entity
public class Address {@Idprivate 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();}@PersistenceContextprivate EntityManager em;
}

以下代码来自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 {@Idprivate int id;private String name;private long salary;@Temporal(TemporalType.DATE)private Date startDate;@OneToOneprivate Address address;@OneToMany(mappedBy="employee")private Collection<Phone> phones = new ArrayList<Phone>();@ManyToOneprivate Department department;@ManyToOneprivate 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 {@Idprotected int id;protected String name;@ManyToManyprotected 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();}
}

下载 Query_Entity_Parameter_Value.zip

以下是数据库转储。

Table Name: ADDRESSTable Name: DEPARTMENTRow:Column Name: ID,Column Type: INTEGER:Column Value: 1Column Name: NAME,Column Type: VARCHAR:Column Value: DesignTable Name: PHONETable Name: PROFESSORRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: NAME,Column Type: VARCHAR:Column Value: TOMColumn Name: SALARY,Column Type: BIGINT:Column Value: 1111Column Name: STARTDATE,Column Type: DATE:Column Value: nullColumn Name: ADDRESS_ID,Column Type: INTEGER:Column Value: nullColumn Name: DEPARTMENT_ID,Column Type: INTEGER:Column Value: 1Column Name: MANAGER_ID,Column Type: INTEGER:Column Value: nullTable Name: PROJECTTable Name: PROJECT_PROFESSOR

JPA 查询编号索引参数示例

JPA教程 - JPA查询编号索引参数示例

以下代码显示了如何在JPQL中使用数字索引参数。

Collection expired = em.createQuery("SELECT u FROM Professor u WHERE u.id > ?1").setParameter(1, 1).getResultList();

例子

以下代码来自Address.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;@Entity
public class Address {@Idprivate 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();}}

下面的代码来自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 {@Idprivate 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();}
}

下面的代码来自PersonDaoImpl.java。

package cn.w3cschool.common;import java.util.Collection;
import java.util.Iterator;import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;import org.springframework.transaction.annotation.Transactional;@Transactional
public class PersonDaoImpl {public void test() {prepareData();Collection expired = em.createQuery("SELECT u FROM Professor u WHERE u.id > ?1").setParameter(1,1).getResultList();for (Iterator i = expired.iterator(); i.hasNext();) {Professor u = (Professor) i.next();printResult(u);}}private void prepareData() {Address address = new Address();address.setState("BC");Professor p = new Professor();p.setId(0);p.setName("TOM");p.setSalary(1111L);p.setAddress(address);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(address);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();}@PersistenceContextprivate EntityManager em;
}

以下代码来自Phone.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;@Entity
public class Phone {@Idprivate long id;private String number;private String type;@ManyToOneProfessor 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.NamedNativeQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;@Entity
@Table(name = "EMP")
public class Professor {@Idprivate int id;private String name;private long salary;@Temporal(TemporalType.DATE)private Date startDate;@OneToOneprivate Address address;@OneToMany(mappedBy="employee")private Collection<Phone> phones = new ArrayList<Phone>();@ManyToOneprivate Department department;@ManyToOneprivate 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 {@Idprotected int id;protected String name;@ManyToManyprotected 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();}
}

下载 Query_Number_Indexed_Parameters.zip

以下是数据库转储。

Table Name: ADDRESSRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: CITY,Column Type: VARCHAR:Column Value: nullColumn Name: STATE,Column Type: VARCHAR:Column Value: BCColumn Name: STREET,Column Type: VARCHAR:Column Value: nullColumn Name: ZIP,Column Type: VARCHAR:Column Value: nullTable Name: DEPARTMENTRow:Column Name: ID,Column Type: INTEGER:Column Value: 1Column Name: NAME,Column Type: VARCHAR:Column Value: DesignTable Name: EMPRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: NAME,Column Type: VARCHAR:Column Value: TOMColumn Name: SALARY,Column Type: BIGINT:Column Value: 1111Column Name: STARTDATE,Column Type: DATE:Column Value: nullColumn Name: ADDRESS_ID,Column Type: INTEGER:Column Value: 0Column Name: DEPARTMENT_ID,Column Type: INTEGER:Column Value: 1Column Name: MANAGER_ID,Column Type: INTEGER:Column Value: nullTable Name: PHONERow:Column Name: ID,Column Type: BIGINT:Column Value: 1Column Name: NUMBER,Column Type: VARCHAR:Column Value: 111-111-1111Column Name: TYPE,Column Type: VARCHAR:Column Value: nullColumn Name: EMPLOYEE_ID,Column Type: INTEGER:Column Value: 0Table Name: PROJECTTable Name: PROJECT_EMP

JPA 查询日期参数示例

JPA教程 - JPA查询日期参数示例

我们可以在查询中使用日期类型值。

以下代码使用EntityManager创建具有两个参数的查询。

然后它传递两个日期类型值。

em.createQuery("SELECT e " +"FROM Professor e " +"WHERE e.startDate BETWEEN :start AND :end").setParameter("start", new Date(), TemporalType.DATE).setParameter("end", new Date(), TemporalType.DATE).getResultList();

例子

以下代码来自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.NamedNativeQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;@Entity
@Table(name = "EMP")
public class Professor {@Idprivate int id;private String name;private long salary;@Temporal(TemporalType.DATE)private Date startDate;@OneToOneprivate Address address;@OneToMany(mappedBy="employee")private Collection<Phone> phones = new ArrayList<Phone>();@ManyToOneprivate Department department;@ManyToOneprivate 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 {@Idprotected int id;protected String name;@ManyToManyprotected 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();}
}

下面的代码来自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 {@Idprivate 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();}
}

以下代码来自Phone.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;@Entity
public class Phone {@Idprivate long id;private String number;private String type;@ManyToOneProfessor 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();}
}

以下代码来自Address.java。

package cn.w3cschool.common;import javax.persistence.Entity;
import javax.persistence.Id;@Entity
public class Address {@Idprivate 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.Collection;
import java.util.Date;
import java.util.Iterator;import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TemporalType;import org.springframework.transaction.annotation.Transactional;@Transactional
public class PersonDaoImpl {public void test() {prepareData();Collection<Professor> c =  em.createQuery("SELECT e " +"FROM Professor e " +"WHERE e.startDate BETWEEN :start AND :end").setParameter("start", new Date(), TemporalType.DATE).setParameter("end", new Date(), TemporalType.DATE).getResultList();for (Iterator i = c.iterator(); i.hasNext();) {Professor u = (Professor) i.next();printResult(u);}}private void prepareData() {Address address = new Address();address.setState("BC");Professor p = new Professor();p.setId(0);p.setName("TOM");p.setSalary(1111L);p.setAddress(address);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(address);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();}@PersistenceContextprivate EntityManager em;
}

下载 Query_Date_Parameters.zip

以下是数据库转储。

Table Name: ADDRESSRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: CITY,Column Type: VARCHAR:Column Value: nullColumn Name: STATE,Column Type: VARCHAR:Column Value: BCColumn Name: STREET,Column Type: VARCHAR:Column Value: nullColumn Name: ZIP,Column Type: VARCHAR:Column Value: nullTable Name: DEPARTMENTRow:Column Name: ID,Column Type: INTEGER:Column Value: 1Column Name: NAME,Column Type: VARCHAR:Column Value: DesignTable Name: EMPRow:Column Name: ID,Column Type: INTEGER:Column Value: 0Column Name: NAME,Column Type: VARCHAR:Column Value: TOMColumn Name: SALARY,Column Type: BIGINT:Column Value: 1111Column Name: STARTDATE,Column Type: DATE:Column Value: nullColumn Name: ADDRESS_ID,Column Type: INTEGER:Column Value: 0Column Name: DEPARTMENT_ID,Column Type: INTEGER:Column Value: 1Column Name: MANAGER_ID,Column Type: INTEGER:Column Value: nullTable Name: PHONERow:Column Name: ID,Column Type: BIGINT:Column Value: 1Column Name: NUMBER,Column Type: VARCHAR:Column Value: 111-111-1111Column Name: TYPE,Column Type: VARCHAR:Column Value: nullColumn Name: EMPLOYEE_ID,Column Type: INTEGER:Column Value: 0Table Name: PROJECTTable Name: PROJECT_EMP

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/889810.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【操作系统1】一篇文章便可入门操作系统

操作系统 (Operating System,OS)是一种系统软件&#xff0c;它负责管理计算机的硬件和软件资源。它的主要任务是组织和调度计算机的工作&#xff0c;并分配资源给用户和其他软件。操作系统为用户和软件提供了方便的接口和环境。它是计算机系统中最基本的软件之一。 一、操作系…

μC/OS-Ⅱ源码学习(6)---事件标志组

快速回顾 μC/OS-Ⅱ中的多任务 μC/OS-Ⅱ源码学习(1)---多任务系统的实现 μC/OS-Ⅱ源码学习(2)---多任务系统的实现(下) μC/OS-Ⅱ源码学习(3)---事件模型 μC/OS-Ⅱ源码学习(4)---信号量 μC/OS-Ⅱ源码学习(5)---消息队列 本文进一步解析事件模型中&#xff0c;事件标志…

【经验分享】OpenHarmony5.0.0-release编译RK3568不过问题(已解决)

问题描述 根据操作手册正常拉取代码&#xff0c;然后编译OpenHarmony5.0.0版本rk3568项目 编译命令 ./build.sh --product-name rk3568 --ccache出现如下报错 然后真正开始出错的位置是下面这句log FAILED: ../kernel/src_tmp/linux-5.10/boot_linux ../kernel/checkpoint/c…

C++重点和练习-----多态

rpg.cpp: #include <iostream>using namespace std;/*模拟一个游戏场景有一个英雄&#xff1a;初始所有属性为1atk,def,apd,hp游戏当中有以下3种武器长剑Sword&#xff1a; 装备该武器获得 1atx&#xff0c;1def短剑Blade&#xff1a; 装备该武器获得 1atk&#xff0c;1…

Qt之点击鼠标右键创建菜单栏使用(六)

Qt开发 系列文章 - menu&#xff08;六&#xff09; 目录 前言 一、示例演示 二、菜单栏 1.MenuBar 2.Menu 总结 前言 QMainWindow是一个为用户提供主窗口程序的类&#xff0c;包含一个菜单栏&#xff08;menubar&#xff09;、多个工具栏(toolbars)、一个状态栏(status…

天猫魔盒M17/M17S_超级UI 线刷固件包-可救砖(刷机取消双勾)

在智能电视盒子的领域中&#xff0c;天猫魔盒 M17 以其独特魅力占据一席之地&#xff0c;然而&#xff0c;原厂设置有时难以满足进阶用户的多元需求。此刻&#xff0c;刷机成为开启全新体验的关键钥匙&#xff0c;为您的盒子注入鲜活能量。 一、卓越固件特性概览 此款精心打造的…

Elasticsearch 7.x入门学习-Spring Data Elasticsearch框架

1 Spring Data框架 Spring Data 是一个用于简化数据库、非关系型数据库、索引库访问&#xff0c;并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷&#xff0c;并支持 map-reduce 框架和云计算数据服务。 Spring Data 可以极大的简化 JPA的写法&#xff0c;…

【落羽的落羽 C语言篇】一些常见的字符函数、字符串函数、内存函数

文章目录 一、字符函数1. 字符分类函数2. 字符转换函数 二、字符串函数1. strlen的使用和模拟实现使用模拟实现 2. strcpy的使用和模拟实现使用模拟实现 3. strcat的使用和模拟实现使用模拟实现 4. strcmp的使用和模拟实现使用模拟实现 5. strncpy的使用6. strncat的使用7. str…

JAVA:访问者模式(Visitor Pattern)的技术指南

1、简述 访问者模式(Visitor Pattern)是一种行为型设计模式,允许你将操作分离到不同的对象中,而无需修改对象本身的结构。这种模式特别适合复杂对象结构中对其元素进行操作的场景。 本文将介绍访问者模式的核心概念、优缺点,并通过详细代码示例展示如何在实际应用中实现…

小米自研系统Vela全面开源:开启物联网新时代的技术革新之旅

目录 Vela系统的技术特点 1. 高性能与低功耗的完美平衡 2. 高度可扩展性与模块化设计 3. 强大的安全机制 4. 跨平台兼容性 Vela系统的应用场景 1. 智能家居领域 2. 工业物联网领域 3. 医疗健康领域 4. 智慧城市领域 Vela系统的深远影响 1. 推动物联…

Linux/CentOS编译TensorFlow

很多时候为了方便图省事&#xff0c;是通过pip安装TensorFlow的&#xff0c;然而很不幸运行的服务器不支持AVX指令&#xff0c;引入模块的时候会报错&#xff1a; The TensorFlow library was compiled to use AVX instructions, but these aren’t available on your machine.…

2021陇剑杯——流量分析

JWT简介 JWT&#xff08;JSON Web Token&#xff09;是一种开放标准&#xff08;RFC 7519&#xff09;&#xff0c;用于在网络应用环境中以一种紧凑的、URL安全的方式传递声明&#xff08;Claims&#xff09;。JWT通常用于身份验证、信息交换以及验证消息的完整性。JWT通过在不…

visual studio 2022 c++使用教程

介绍 c开发windows一般都是visual studio&#xff0c;linux一般是vscode&#xff0c;但vscode调试c不方便&#xff0c;所以很多情况都是2套代码&#xff0c;在windows上用vs开发方便&#xff0c;在转到linux。 安装 1、官网下载vs2022企业版–选择桌面开发–安装位置–安装–…

Grafana配置告警规则推送企微机器人服务器资源告警

前提 已经部署Grafana&#xff0c;并且dashboard接入数据 大屏编号地址&#xff1a;Node Exporter Full | Grafana Labs 创建企微机器人 备注&#xff1a;群里若有第三方外部人员不能创建 机器人创建完成&#xff0c;记录下来Webhook地址 Grafana配置告警消息模板 {{ define &…

yolov7-搭建及测试

1.环境配置 参考链接&#xff0c;建立环境 2.YOLOv7代码下载 代码及论文地址&#xff1a; GitHub - WongKinYiu/yolov7: Implementation of paper - YOLOv7: Trainable bag-of-freebies sets new state-of-the-art for real-time object detectors 下载zip后解压 注意&am…

HCIA-Access V2.5_2_2_2网络通信基础_IP编址与路由

网络层数据封装 首先IP地址封装在网络层&#xff0c;它用于标识一台网络设备&#xff0c;其中IP地址分为两个部分&#xff0c;网络地址和主机地址&#xff0c;通过我们采用点分十进制的形式进行表示。 IP地址分类 对IP地址而言&#xff0c;它细分为五类&#xff0c;A,B,C,D,E,…

信号处理相关的东东(学习解惑)

信号处理相关的东东&#xff08;学习解惑&#xff09; 所有内容学习自知乎专栏&#xff0c;https://www.zhihu.com/column/xinhao&#xff0c;写的很好&#xff0c;值得反复学习 时频域分析的一些常用概念 FROM&#xff1a;https://zhuanlan.zhihu.com/p/35742606 1、相加性…

【cocos creator】按照行列数创建格子布局

调用 this.creatLayout(5, 5, this.boxNode, this.rootNode) //限制数量 this.creatLayout(5, 5, this.boxNode, this.rootNode, cc.v3(0, 0), 10, 10, 23) /*** 创建格子布局* param xCount 列数量* param yCount 行数量* param prefab 预制体* param root 根节点* param root…

WPF 控件

<div id"content_views" class"htmledit_views"><p id"main-toc"><strong>目录</strong></p> WPF基础控件 按钮控件&#xff1a; Button:按钮 RepeatButton:长按按钮 RadioButton:单选按钮 数据显示控件 Te…

java中List集合小练习

题目&#xff1a;将1~100之间所有正整数存放在一个List集合中&#xff0c;并将集合索引位置时10的对象从集合中移除。 代码&#xff1a; import java.util.ArrayList; import java.util.List;public class ListTest {public ListTest(){List<Integer> listnew ArrayLis…