Well the question pretty much says everything. Using JPARepository how do I update an entity?
JPARepository has only a save method, which does not tell me if it's create or update actually. For example, I insert a simple Object to the database User, which has three fields: firstname, lastname and age:
@Entity public class User { private String firstname; private String lastname; //Setters and getters for age omitted, but they are the same as with firstname and lastname. private int age; @Column public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } @Column public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } private long userId; @Id @GeneratedValue(strategy=GenerationType.AUTO) public long getUserId(){ return this.userId; } public void setUserId(long userId){ this.userId = userId; } } Then I simply call save(), which at this point is actually an insert into database:
User user1 = new User(); user1.setFirstname("john"); user1.setLastname("dew"); user1.setAge(16); userService.saveUser(user1);// This call is actually using the JPARepository: userRepository.save(user); So far so good. Now I want to update this user, say change his age. For this purpose I could use a Query, either QueryDSL or NamedQuery, whatever. But, considering I just want to use spring-data-jpa and the JPARepository, how do I tell it that instead of an insert I want to do an update?
Specifically, how do I tell spring-data-jpa that users with the same username and firstname are actually EQUAL and that the existing entity supposed to be updated? Overriding equals did not solve this problem.
