Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

346
Views
PostgreSQL maunally inserted record vs Spring JPA Save with sequence

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!