Home > Software engineering >  Document field as primary key not working
Document field as primary key not working

Time:08-18

I have a "document" field that needs to be a primary key and must be unique, but every time I do a POST with the same document it updates the document and doesn't send a BAD_REQUEST

My entity:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"document"})})
public class Cliente {

    @Id
    @Column(unique=true, updatable = false)
    @NotBlank @NotNull
    private String document;
    @NotBlank
    private String name;
    @NotNull
    private LocalDateTime date;
}

When I try to make a new POST with the same document it just updates what is saved in the database.

"Hibernate: update client set date=?, name=? where document=?"

CodePudding user response:

The problem is that Spring Data JPA, when you call Repository#save, assumes that you want to update an existing entity when the passed in entity object has the id attribute set. You will have to inject a EntityManager in your code and instead call EntityManager#persist if you want to make sure that Hibernate tries to do an insert, in which case you'd get a constraint violation exception, just as you expect.

  • Related