JPA更新實體
JPA允許我們通過更新實體來更改數據庫中的記錄。
JPA實體更新示例
在這裏,我們將演示如何根據主鍵更新學生的年齡。
完整的項目代碼如下所示 -
這個例子包含以下步驟 -
第1步: 在com.yiibai.jpa.student
包下創建一個名爲StudentEntity.java
的實體類,它包含屬性:s_id
,s_name
和s_age
。
文件:StudentEntity.java 的代碼如下 -
package com.yiibai.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;
}
}
第2步: 將實體類和其他數據庫配置映射到persistence.xml
文件中。
文件:persistence.xml 的代碼如下 -
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Student_details">
<class>com.yiibai.jpa.student.StudentEntity</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="123456" />
<property name="eclipselink.logging.level" value="SEVERE" />
<property name="eclipselink.ddl-generation"
value="create-or-extend-tables" />
</properties>
</persistence-unit>
</persistence>
在com.yiibai.jpa.student
包下創建一個名爲UpdateStudent.java
的持久化類,以便將實體對象與數據保持一致。
文件:UpdateStudent.java 的代碼如下 -
package com.yiibai.jpa.student;
import javax.persistence.*;
import com.yiibai.jpa.student.*;
public class UpdateStudent {
public static void main(String args[]) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Student_details");
EntityManager em = emf.createEntityManager();
StudentEntity s = em.find(StudentEntity.class, 1001);
System.out.println("Before Updation");
System.out.println("Student id = " + s.getS_id());
System.out.println("Student Name = " + s.getS_name());
System.out.println("Student Age = " + s.getS_age());
s.setS_age(30);
System.out.println("After Updation");
System.out.println("Student id = " + s.getS_id());
System.out.println("Student Name = " + s.getS_name());
System.out.println("Student Age = " + s.getS_age());
}
}
執行上面示例代碼,得到以下結果 -
Before Updation
Student id = 1001
Student Name = Maxsu
Student Age = 26
After Updation
Student id = 1001
Student Name = Maxsu
Student Age = 30