php editor Apple will take you to deeply explore the core concepts of Java JPA in this article: entities, mapping and queries. As the complexity of modern applications increases, an understanding of JPA becomes critical. This article will help you understand the key concepts in JPA so that you can better apply them to actual projects.
@Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; // 省略 getter 和 setter 方法 }
Mapping is the mechanism used by JPA to map properties in an entity class to fields in the database . JPA provides many types of mappings, including:
Mapping can also specify the attribute type, length, whether it is allowed to be empty, and other information.
@Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 50, nullable = false) private String name; @Column(nullable = false) private int age; // 省略 getter 和 setter 方法 }
JPA provides a variety of query mechanisms, including:
// JPQL 查询 List<Person> persons = entityManager.createQuery("SELECT p FROM Person p WHERE p.age > 18", Person.class) .getResultList(); // Criteria API 查询 CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Person> cq = cb.createQuery(Person.class); Root<Person> root = cq.from(Person.class); cq.select(root).where(cb.gt(root.get("age"), 18)); List<Person> persons = entityManager.createQuery(cq).getResultList(); // 本机查询 List<Person> persons = entityManager.createNativeQuery("SELECT * FROM Person WHERE age > 18", Person.class) .getResultList();
JPA is a powerful persistence framework that provides unified access to relational databases. By using JPA, we can easily persist Java objects into the database and query entity objects using JPQL, Criteria API or native queries.
The above is the detailed content of Dive into the core concepts of Java JPA: entities, mappings, and queries. For more information, please follow other related articles on the PHP Chinese website!