要从数据库中删除一条记录, EntityManager接口提供了remove()方法。 remove()方法使用主键删除特定记录。
JPA实体删除示例
【JPA删除实体】在这里, 我们将删除学生的特定记录。
本示例包含以下步骤:-
- 在com.srcmini.jpa.student包下创建一个名为StudentEntity.java的实体类, 该实体类包含s_id, s_name和s_age属性。
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>
<
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>
Deletion.java
package com.srcmini.jpa.delete;
import javax.persistence.*;
import com.srcmini.jpa.student.*;
public class DeleteStudent { public static void main(String args[]) { EntityManagerFactory emf=Persistence.createEntityManagerFactory("Student_details");
EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
StudentEntity s=em.find(StudentEntity.class, 102);
em.remove(s);
em.getTransaction().commit();
emf.close();
em.close();
}}
输出:
程序执行后, 将在MySQL工作台下生成Student表, 该表包含Student详细信息。要获取数据, 请在MySQL中从学生查询中运行select *。
删除前
文章图片
删除后
文章图片
推荐阅读
- JPA实体介绍
- JPA条件WHERE子句
- JPA条件选择子句
- JPA ORDER BY子句
- JPA标准的Having子句
- JPA条件 GROUP BY子句
- PSD标准API
- JPA创建实体
- JPA集合映射