How to persist objects in a table if I don’t already have the foreign key?

Asked

Viewed 75 times

0

I have a class of Equipment that has a Scheduling list. They are mapped like this:

@Entity
@Table(schema = "pesquisa", name = "sre_equipamento")
public class Equipamento implements Serializable {

...

@OneToMany(cascade = CascadeType.ALL, mappedBy = "equipamento")
private List<AgendaFuncionamento> listaAgendaFuncionamento = new ArrayList<>();

...

}

@Entity
@Table(schema = "pesquisa", name = "sre_agenda_funcionamento")
public class AgendaFuncionamento implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "dia_semana")
    private int diaSemana;

    @Column(name = "hora_inicio")
    //@Temporal(TemporalType.TIME)
    private LocalTime horarioInicial;

    @Column(name = "hora_fim")
    // @Temporal(TemporalType.TIME)
    private LocalTime horarioFinal;

    @JoinColumn(name = "id_equipamento", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Equipamento equipamento;

    @Transient
    private List<AgendaFuncionamento> listaDisponibilidade;
    
    ...
    
    }

When I call the Insert method to record it is recording the contents of the listAgendaAutomatically function in the sre_schedule_working table and as I do not have the key of the equipment I get the error:

ERROR: null value in column "id_equipamento" violates not-null constraint
  Detalhe: Failing row contains (16, null, 1, 01:31:00, 02:10:00).

From what I understand, he’s trying to record the list first. I made a Repository for him to record the contents of the list after recording the equipment, but he’s trying to record the list automatically.

How can I fix this?

1 answer

0


I was able to solve it by removing Cascadetype.ALL, because Cascadetype.PERSIST was causing this...

@Entity
@Table(schema = "pesquisa", name = "sre_equipamento")
public class Equipamento implements Serializable {

...

@OneToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE}, mappedBy = "equipamento")
private List<AgendaFuncionamento> listaAgendaFuncionamento = new ArrayList<>();

...

}

Browser other questions tagged

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