JPA插入实体

在JPA中, 我们可以轻松地通过实体将数据插入数据库。 EntityManager提供了persist()方法来插入记录。
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.persist包下创建一个名为PersistStudent.java的持久性类, 以将实体对象与数据持久化。
PersistStudent.java
package com.srcmini.jpa.persist; import com.srcmini.jpa.student.*; import javax.persistence.*; public class PersistStudent { public static void main(String args[]) {EntityManagerFactory emf=Persistence.createEntityManagerFactory("Student_details"); EntityManager em=emf.createEntityManager(); em.getTransaction().begin(); StudentEntity s1=new StudentEntity(); s1.setS_id(101); s1.setS_name("Gaurav"); s1.setS_age(24); StudentEntity s2=new StudentEntity(); s2.setS_id(102); s2.setS_name("Ronit"); s2.setS_age(22); StudentEntity s3=new StudentEntity(); s3.setS_id(103); s3.setS_name("Rahul"); s3.setS_age(26); em.persist(s1); em.persist(s2); em.persist(s3); em.getTransaction().commit(); emf.close(); em.close(); }}

输出:
【JPA插入实体】程序执行后, 将在MySQL工作台下生成Student表, 该表包含学生详细信息, 要获取数据, 请在MySQL中从Student查询中运行select *。
JPA插入实体

文章图片

    推荐阅读