Home > Software design >  Hibernate JPA Entity want to persisit only one column
Hibernate JPA Entity want to persisit only one column

Time:02-25

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?

CodePudding user response:

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

CodePudding user response:

The default behavior is that when you update a Hibernate entity, all fields on the entity will be updated in the underlying database record. Note that this is not wrong, assuming the same values are being used for updates on columns as the values which were initially read.

If you really want an update of just a single column, you may create a JPA repository method for that, e.g.

@Modifying
@Query("update MyTable m set m.name = :name where m.id = :id")
void updateName(@Param("name") String name, @Param("id") Long id);

If you examine the SQL generated by the above, it will really only update one column.

Note that on some databases, updates to columns where the value does not change will actually be ignored, q.v. this SO question.

  • Related