Tenho a primeira entidade
private static final long serialVersionUID = 2405172041950251807L;
private static final String CAMPO_CODIGO = "CODIGO";
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_TABLE1")
@SequenceGenerator(name = "SEQ_TABLE1", sequenceName = "SEQ_TABLE1", allocationSize = 1)
@NotNull
@Column(name = "CODIGO")
private Long codigo;
@Column(name = "table1Field1")
private Short table1Field1;
@Column(name = "table1Field2")
private String table1Field2;
@Column(name = "table1Field3")
private Long table1Field3;
@OneToMany(
mappedBy = "table1",
cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE},
orphanRemoval = true
)
private List<RelTable1Table2> relTable1Table2 = new ArrayList<>();
A outra entidade
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_TABLE2")
@SequenceGenerator(name = "SEQ_TABLE2", sequenceName = "SEQ_TABLE2", allocationSize = 1)
@NotNull
@Column(name = "CODIGO")
private Long codigo;
@Column(name = "table2Field1")
private String table2Field1;
@Column(name = "table2Field2")
private Short table2Field2;
@OneToMany(
mappedBy = "table2",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<RelTab1Tab2> relTab1Tab2 = new ArrayList<>();
E a entidade que relaciona as duas entidades.
private static final long serialVersionUID = 2405172041950251807L;
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CODIGO_TAB_2", referencedColumnName = "CODIGO")
private Table2 table2;
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CODIGO_TAB_1", referencedColumnName = "CODIGO")
private Table1 table1;
Classe que faz cria o id para a entidade de relacionamento
private Long table1;
private Long table2;
Qual a forma correta de inserir e atualizar os dados presentes nessas três tabelas, utilizando os recursos do jpa ? A princicio está sendo feito assim
private void persisteEatualiza(Table1SaveData table1SaveData){
Table1 table1 = table1Mapper.toEntity(table1SaveData.getTable1());
List<Table2> table2s = table2Mapper.toEntity(table1SaveData.getTable2());
List<RelTab1Tab2> relTab1Tab2s = new ArrayList<>();
for(Table2 table2 : table2s){
RelTab1Tab2 relTab1Tab2 = new RelTab1Tab2();
relTab1Tab2.setTable2(table2);
relTab1Tab2.setTable1(table1);
relTab1Tab2s.add(relTab1Tab2);
}
table1.setRelTab1Tab2(relTab1Tab2s);
table1Repository.save(table1);