Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hibernate JPA Entity want to persisit only one column

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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=?

Ref Tutorial

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading