Here is my entity and table structure as below
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
@SequenceGenerator(name = "seq", sequenceName = "user_data_seq")
private Integer id;
@Column(name = "FName")
private String fname;
@Column(name = "LName")
Private String lname;
CREATE TABLE user
(
id integer NOT NULL DEFAULT nextval('user_data_seq'::regclass),
fname character varying(32) COLLATE pg_catalog."default" NOT NULL,,
lname character varying(32) COLLATE pg_catalog."default" NOT NULL
CONSTRAINT pk_user PRIMARY KEY (id),
CONSTRAINT user_fname_unique UNIQUE (fname)
}
I have made one manual entry in USER through pgAdmin, its inserted with the latest sequence value.
INSERT INTO user(fname, lname) VALUES('AAA', 'BBB');
Now application is using and trying to update the LName for the existing record. But looks like JPA is considering this as new entry and trying re-insert, due to that unique constraint violation error is occurring.
public User updateLName(final User user) {
User userToUpdate = userRepository.findById(user.getId());
userToUpdate.setLName("CCC");
userToUpdate = userRepository.save(userToUpdate);
return userToUpdate;
}
The below code (if condition) from Spring JPA, is still returning as true and make the record to insert as NEW :
org.springframework.data.jpa.repository.support.SimpleJpaRepository
@Transactional
public <S extends T> S save(S entity) {
if (this.entityInformation.isNew(entity)) {
this.em.persist(entity);
return entity;
} else {
return this.em.merge(entity);
}
}
But this wont be a problem for the records inserted through application already and again able to update.
The identity of entities is defined by their primary keys. So you have to specify which data you want to update. To update existing using save() method you can fetch the existing data by id.
User userToUpdate = userRepository.getOne(id);
The update its data
userToUpdate.setFname(userDto.getFName());
And finally, call the save method it update the data in database
userRepository.save(userToUpdate);