Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

354
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda