简体   繁体   中英

Updating the same table on the different applications using hibernate

I have 2 nodes of application and both of them updates the same db table. However, updated columns are different. In here the problem occurs and secondly running application updates the whole row instead single column. Let's deep dive into problem explanation.

The table name is "student" and it has 3 columns. Assuming ID, column1,column2

initial state of the row is ID=1, column1="abc", column2="xyz" The problematic scenario steps are below

  • App-instance-1: reads the row and keep it in persistent state.
  • App-instance-2: reads the row and keep it in persistent state.
  • App-instance-1: updates the pojo attribute column1 as to be "ABC" ( column1="ABC" , column2="xyz").
  • App-instance-2: updates the pojo attribute column2 as to be "XYZ" (column1="abc", column2="XYZ" ).
  • App-instance-1: merges the pojo into db table and the row looks like ID=1, column1="ABC", column2="xyz"
  • App-instance-2: merges the pojo into db table and the row looks like ID=1, column1="abc", column2="XYZ"

Finally, App-instances override the each other' s columns. I want to see the final row as column1="ABC", column2="XYZ" . However, it is column1="abc", column2="XYZ" .

My question is that why App-instance-1 updates the column2 even if no changes on the column2. column2 is not dirty on the instance-1. How can i overcome this issue?

@Entity
@Table("student")
public class Student {
    private Long ID;
    private String column1;
    private String column2;
    
    // Assuming other definations are ok.
}

Thanks in advance.

As far as my knowledge goes you could try one of those 2 methods:

  • Use optimistic locking (ex. @Version provided by Hibernate)
  • Create custom queries to update only one field instead of updating whole entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM