I had previously modelled a ManyToMany relation in JPA but now I had to make it OneToMany and ManyToOne. I had some input from a friend but now I am unable to save the join table correctly.
These are my entities:
Label:
public class Label implements Serializable {
@Id
@GeneratedValue()
@Column(updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID id;
// BEFORE
// @OneToMany
@OneToMany(mappedBy = "technology")
private Set<TechnologyLabel> technology;
//getters setters equal hashcode
}
Technology:
public class Technology implements Serializable {
@Id
@GeneratedValue
@Column(updatable = false, nullable = false, columnDefinition = "BINARY(16)")
private UUID uuid;
@Column(nullable = false, length = 30)
private String technologyName;
// BEFORE
// @OneToMany
@OneToMany(mappedBy = "label")
private Set<TechnologyLabel> labels;
//getters setters equal hashcode
}
TechnologyLabel:
public class TechnologyLabel {
@Id
@EqualsAndHashCode.Include
UUID technologyId;
@Id
@EqualsAndHashCode.Include
@Column(name = "label__id")
UUID labelId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(insertable = false, updatable = false)
Technology technology;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(insertable = false, updatable = false)
Label label;
//getters setters equal hashcode
@Data
public static class PK implements Serializable {
UUID technologyId;
UUID labelId;
}
}
My issues is in how to save TechnologyLabel
. What I do is:
- create
label
and save it in DB - create
technology
and save it in DB - create
technologyLabel
addlabel
andtechnology
and save it in DB
an example of step 3 is:
var technologyLabelList = new ArrayList<TechnologyLabel>();
for (var t : technologies) {
for (var l : labels) {
var technologyLabel = new TechnologyLabel();
technologyLabel.setTechnology(t);
technologyLabel.setLabelId(l.getId());
technologyLabel.setTechnologyId(t.getUuid());
technologyLabel.setLabel(l);
technologyLabelList.add(technologyLabel);
}
}
technologyLabelRepository.saveAll(technologyLabelList);
like this my program runs and the table is created. The issue I have is that I have to manually set the labelId
and technologyId
. The resulting TechnologyLabel table
looks weird to me though as it has the IDs twice and once empty.
I had to set the name of the column for the labelId
to label__id
or I would get the following error:
Caused by: org.hibernate.DuplicateMappingException: Table [technology_label] contains physical column name [label_id] referred to by multiple logical column names: [label_id], [labelId]