Please suggest me a way to update one column in JPA Entity.
My code
@Entity
@Table(name = "my_table")
public class MyTable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false)
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "mobile")
private Integer mobile;
@Column(name = "address")
private String address;
@Column(name = "gender")
private String gender;
}
when I want to update my entity it updates all the columns but only wants to update only one column
MyTable myTable = myRepo.findMyTableById(1);
myTable.setName("ra");
repo.save();
in this case query printing
update Account set name=?, mobile=?, address=?, gender=? where id=?
but I want to update only one column value why it is updating all the columns?
>Solution :
You can use @DynamicUpdate annotation in your entity class. This will help you to update only one column
Actually, when we use @DynamicUpdate on an entity, Hibernate does not use the cached SQL statement for the update. Instead, it will generate a SQL statement each time we update the entity. This generated SQL includes only the changed columns.
In order to find out the changed columns, Hibernate needs to track the state of the current entity. So, when we change any field of an entity, it compares the current and the modified states of the entity.
So, I hope this will print now on your console.
update my_table set name=? where id=?