JPA查找实体

为了找到实体, EntityManger接口提供了find()方法, 该方法根据主键搜索元素。
JPA实体查找示例 在这里, 我们将搜索特定记录并在控制台上将其获取。
本示例包含以下步骤:-

  • 在com.srcmini.jpa.student包下创建一个名为StudentEntity.java的实体类, 该实体类包含s_id, s_name, s_age属性。
StudentEntity.java
package com.srcmini.jpa.student; import javax.persistence.*; @Entity@Table(name="student")public class StudentEntity { @Id private int s_id; private String s_name; private int s_age; public StudentEntity(int s_id, String s_name, int s_age) {super(); this.s_id = s_id; this.s_name = s_name; this.s_age = s_age; } public StudentEntity() {super(); } public int getS_id() {return s_id; } public void setS_id(int s_id) {this.s_id = s_id; } public String getS_name() {return s_name; } public void setS_name(String s_name) {this.s_name = s_name; } public int getS_age() {return s_age; } public void setS_age(int s_age) {this.s_age = s_age; } }

  • 现在, 在Persistence.xml文件中映射实体类和其他数据库配置。
Persistence.xml
< persistence> < persistence-unit name="Student_details"> < class> com.srcmini.jpa.student.StudentEntity< /class> < properties> < property name="javax.persistence.jdbc.driver" value="http://www.srcmini.com/com.mysql.jdbc.Driver"/> < property name="javax.persistence.jdbc.url" value="http://www.srcmini.com/jdbc:mysql://localhost:3306/studentdata"/> < property name="javax.persistence.jdbc.user" value="http://www.srcmini.com/root"/> < property name="javax.persistence.jdbc.password" value=""/> < property name="eclipselink.logging.level" value="http://www.srcmini.com/SEVERE"/> < property name="eclipselink.ddl-generation" value="http://www.srcmini.com/create-or-extend-tables"/> < /properties> < /persistence-unit> < /persistence>

  • 在com.srcmini.jpa.find包下创建一个名为FindStudent.java的持久性类, 以将实体对象与数据持久化。
FindStudent.java
package com.srcmini.jpa.find; import javax.persistence.*; import com.srcmini.jpa.student.*; public class FindStudent { public static void main(String args[]) {EntityManagerFactory emf=Persistence.createEntityManagerFactory("Student_details"); EntityManager em=emf.createEntityManager(); StudentEntity s=em.find(StudentEntity.class, 101); System.out.println("Student id = "+s.getS_id()); System.out.println("Student Name = "+s.getS_name()); System.out.println("Student Age = "+s.getS_age()); }}

【JPA查找实体】输出:
JPA查找实体

文章图片

    推荐阅读