JPA(Java Persistence API)是一种用于管理Java应用中的持久性数据的标准API。它是一种ORM(对象关系映射)技术,可以将Java对象映射到关系数据库中。JPA使用实体来表示数据库中的表,并使用实体之间的关系来表示表之间的关系。
JPA为开发人员提供了一个标准化的方法来访问和更新数据库中的数据。它还可以帮助开发人员避免重复代码和错误,并且可以大大减少开发时间。
JPA使用JPQL(Java Persistence Query Language)作为其查询语言。JPQL是一种面向对象的SQL语言,它使用实体和实体之间的关系来表达SQL中的表和列。JPQL可以执行SELECT、INSERT、UPDATE和DELETE语句,从而帮助开发人员在不直接使用SQL语句的情况下执行数据库查询和修改。
// 使用JPQL进行SELECT 查询 String jpql = "SELECT e FROM Employee e WHERE e.salary > :salary"; Query query = entityManager.createQuery(jpql); query.setParameter("salary", 10000); List<Employee> employees = query.getResultList();
此外,JPA还包含了一些有助于生成和执行JPQL语句的API。例如Criteria API、Metamodel API和EntityManager API都是常用的API之一。Criteria API使用面向对象方法来生成JPQL语句;Metamodel API通过分析实体来生成元数据信息;EntityManager API则是JPA中最重要的API之一,它包含了大多数JPA功能所需要的方法。
JPQL支持的函数表达式如下所示。
函数 | 描述 |
---|---|
ABS(number) | 返回number参数的无符号版本。结果类型与参数类型(整数,浮点型或双精度型)相同。 |
CONCAT(string1,string2) | 连接string1和string2。 |
CURRENT_DATE | 返回数据库服务器定义的当前日期。 |
CURRENT_TIME | 从数据库服务器返回当前时间。 |
CURRENT_TIMESTAMP | 返回数据库服务器的当前时间戳。 |
INDEX(identification variable) | 返回有序列表中实体的位置。 |
LENGTH(string) | 返回字符串参数中的字符数。 |
LOCATE(string1,string2 [,start]) | 返回string1中string1的位置,可选择从start指示的位置开始。如果找不到字符串,结果为零。 |
LOWER(string) | 返回字符串参数的小写形式。 |
MOD(number1,number2) | 返回数字参数number1和number2的模数作为整数。 |
SIZE(collection) | 返回集合中元素的数量,如果集合为空则返回0。 |
SQRT(number) | 返回数字参数的平方根作为double。 |
SUBSTRING(string, start, end) | 返回输入字符串的一部分,从由start开始到length字符指示的索引开始。字符串索引从一个开始。 |
UPPER(string) | 返回字符串参数的大写形式。 |
TRIM([[LEADING | TRAILING | BOTH] [char] FROM] string) | 删除字符串中的前导和/或尾随字符。如果不使用可选的LEADING,TRAILING或BOTH关键字,则删除前导和尾随字符。默认修剪字符是空格字符。 |
以下代码显示如何在JPQL中使用CONCAT,SUBSTRING和LOCATE字符串函数。
em.createQuery( "UPDATE Phone p SET p.number = " + "CONCAT("0",SUBSTRING(p.number," + "LOCATE(p.number, "-"), 4)), p.type = "Business" ") .executeUpdate();
以下代码来自Project.java。
package cn..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(); } }
下面的代码来自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(); em.createQuery( "UPDATE Phone p SET p.number = " + "CONCAT("0",SUBSTRING(p.number," + "LOCATE(p.number, "-"), 4)), p.type = "Business" ") .executeUpdate(); } 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; }
以下代码来自Phone.java。
package cn..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..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()); } }
以下代码来自Address.java。
package cn..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(); } }
下面的代码来自Department.java。
package cn..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(); } }下载 Query_Substring.zip
以下是数据库转储。
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: 0111 Column Name: TYPE, Column Type: VARCHAR: Column Value: Business 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
JPA教程 -JPA查询编号索引参数示例以下代码显示了如何在JPQL中使用数字索引参数。Collection expired = em.createQuery(SELECT u...
Java格式 -Java数字格式类以下两个类可用于格式化和解析数字:java.text.NumberFormatjava.text.DecimalFormat NumberFormat 类可...
Java格式 -Java 打印格式不同的格式字符可以格式化不同数据类型的值。例如,“s用于将值格式化为字符串。Java 打印格式化类型可...
Log4j教程 -Log4j日志格式Apache log4j提供布局对象,以根据各种布局格式化日志数据。布局类层次结构中的顶级类是抽象类org.apac...