个性化阅读
专注于IT技术分析

JPA更新实体

JPA允许我们通过更新实体来更改数据库中的记录。

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="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/studentdata"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="eclipselink.logging.level" value="SEVERE"/>
<property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>
</properties>

	</persistence-unit>
</persistence>
  • 在com.srcmini.jpa.update包下创建一个名为UpdateStudent.java的持久性类, 以将实体对象与数据持久化。

UpdateStudent.java

package com.srcmini.jpa.update;
import javax.persistence.*;

import com.srcmini.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, 102);
		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());
		
		
	}

}

输出:

JPA更新实体
赞(0)
未经允许不得转载:srcmini » JPA更新实体

评论 抢沙发

评论前必须登录!