0

My web application uses Spring (4.2.9), Spring Data (3.2.5), JPA, Hibernate (4.3.8), and MS SQL Server (2014). I am hoping to show the big picture and get the direction to fix this issue.

Here is the class affected:

Class Affected {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long id;
    
    @Version
    private Long version = 1L;

    //getters and setters of the above two fields.
}

Here is another class and saving its object causes the version of the Affected class increases. Note that there is not any kind of relationship between the two classes.

Class Reason {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY )
    private Long id;
}

The service method to fetch an object of Affected objects:

@Override
@Transactional(readOnly = true)
public Survey getAffectedById(Long id) {
    return affectedRepository.findOne(id);
}

This is the flow in a web controller method:

  1. load an Affected object
  2. Create and save an object of Reason in a transaction. In this step, the IP address is extracted from javax.servlet.http.HttpServletRequest and saved in the database to record what IP addresses visited the web application.

After the two steps, the version number of the loaded Affected object increases by 1. If I remove the second step, the version number of the Affected has no change.

I am not able to figure out the reason for this increase. I understand that more code or details are helpful, but I don't want to overwhelm folks here and also the actual code is much more complex than that.

halfer
  • 19,824
  • 17
  • 99
  • 186
curious1
  • 14,155
  • 37
  • 130
  • 231
  • 2
    If there's no relation b/w the 2 classes as you claim, why do you load `Affected` first? What do you do with it? – Abhijit Sarkar Aug 27 '17 at 23:48
  • Hi, I updated the question with description of the second step. – curious1 Aug 28 '17 at 00:42
  • Let me put it differently, since you didn't answer my question. Can you eliminate step 1? I've a hunch what's going on but I don't wanna blurt it out based on your vague description of steps 1 and 2. – Abhijit Sarkar Aug 28 '17 at 01:18
  • 1
    Take a look at https://stackoverflow.com/questions/8190926/transactional-saves-without-calling-update-method and https://stackoverflow.com/questions/5268466/how-does-hibernate-detect-dirty-state-of-an-entity-object – chimmi Aug 28 '17 at 07:29
  • 1
    Since you say this is simplified version of the real code, you could check if in the real code you do something like this: em.find(YourClass.class, id, LockModeType.OPTIMISTIC_FORCE_INCREMENT) – GionJh Aug 28 '17 at 13:18
  • I've voted to close this for now, as the conversation to seek detail/clarity was left unfinished. – halfer Sep 04 '22 at 12:17

0 Answers0