codecamp

JPA 更新示例

JPA教程 - JPA更新示例


以下代码显示了如何通过仅使用映射实体的setter方法来更新实体。

下面的代码在persist方法调用后用setter方法更新name字段。

从下一节中的数据库转储我们可以看到,新的值被保存到数据库。

    Professor emp = new Professor();

    emp.setId(1);
    emp.setName("name");
    em.persist(emp);
    
    emp.setName("New name");

例子

以下代码来自Professor.java。

package cn.w3cschool.common;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity 
@Table(name="EMP")
public class Professor  {
    @Id private int id;
    private String name;
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    public String toString() {
        return "Professor id: " + getId() + " name: " + getName();
    }
}

下面的代码来自PersonDaoImpl.java。

package cn.w3cschool.common;


import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PersonDaoImpl {
  public void test(){
    
    Professor emp = new Professor();

    emp.setId(1);
    emp.setName("name");
    em.persist(emp);
    
    emp.setName("New name");
  }
  @PersistenceContext
  private EntityManager em;
}
下载 Update.zip

以下是数据库转储。

Table Name: EMP
 Row:
    Column Name: ID,
    Column Type: INTEGER:
    Column Value: 1

    Column Name: NAME,
    Column Type: VARCHAR:
    Column Value: New name


JPA 查询更新示例
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }