JPA Tutorial - JPA Update Example








The following code shows how to update an entity by only using the setter method from mapped entity.

The following code updates the name field with setter method after persist method call.

From the database dump in the next section we can see that the new value is saved to database.

    Professor emp = new Professor();

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




Example

The following code is from Professor.java.

package com.java2s.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();
    }
}

The following code is from PersonDaoImpl.java.

package com.java2s.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;
}


Download Update.zip

The following is the database dump.

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

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