Insert data into related entity @Onetoone in Spring Boot(Jpa, Hibernate, Postgre)

Asked

Viewed 199 times

0

I have a one-dimensional relationship (1:1) where the contract has a tenant.

Class User

@Table(name="TB_USER")
@Inheritance(strategy = InheritanceType.JOINED)
public class User implements Serializable {

    @Id
    @Column(name = "cpf")
    private String cpf;
    @NotBlank
    private String nome;
    @NotBlank
    private String email;
}

Class Inquilino

@PrimaryKeyJoinColumn(name="cpf")
public class Inquilino extends User{


    private Boolean status = true;
    @NotBlank
    private String nomeFiador;

    @NotBlank
    private String telefone;
}


  

Class Contract

@Table(name = "TB_CONTRATO")
public class Contrato {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name= "id")
private Long id;

private Boolean status = true;

@NotBlank
private String numContrato;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "cpf")
private Inquilino inquilino;

I made a simple CRUD, and my intention would be to create the tenants and when I create the contract, to send in the body of the request in json. However the error in spring boot appears:

Dcate uplikey value violates Unique Constraint "tb_user_pkey" Detail: Key (Cpf)=(123213) already exists.

I deduced that I could not create the contract with something that was already created on account of identification (more deduction even. But for the project, I would like to have a list of tenants to be chosen and then associate.

I hope I didn’t complicate the understanding.

1 answer

0

Cascade is a bank persistence operation, it will save all entities related to your parent entity.

https://www.devmedia.com.br/cascade-hibernate-conhecendo-diferentes-tipos/28892

As you are using Cascade in your tenant relationship, it will persist and save Tenant along with Contract. That’s why Cpf duplicate key error, is trying to save this entity that was previously saved.

To fix your issue remove the operation Scade leaving only the @Onetoone mapping of your relationship, and try to enter into your service layer manually a tenant already saved in your application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.