这个问题几乎说明了一切。使用JPARepository如何更新实体?
JPARepository只有一个save方法,它不会告诉我它是否实际上是在创建或更新。例如,我插入一个简单的对象数据库的用户,其中有三个领域:firstname
,lastname
和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;
}
}
然后我简单地调用save()
,这实际上是数据库的插入:
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);
到目前为止,一切都很好。现在,我想更新此用户,例如更改其年龄。为此,我可以使用QueryDSL或NamedQuery之类的查询。但是,考虑到我只想使用spring-data-jpa和JPARepository,如何告诉我要进行更新而不是插入?
具体来说,我如何告诉spring-data-jpa用户名和名字相同的用户实际上是EQUAL的,并且现有实体应该更新?覆盖等于不能解决此问题。