I need help to define correctly a @OneToMany JPA annotation. Tried different ways but still get error/issues like the foreign key (visitor_revision_id) is null in the visit
You can achieve it by annotating as follows:
@RepositoryRestResource(export = false)
on VisitorCharacteristicRepository
and creating your own custom controller For VisitorCharacteristic
.
For more understanding you can see - https://youtu.be/FRvtVf9sVjs
class Visitor
public class Visitor {
@Id
@Column(name = "visitor_revision_id")
@GeneratedValue
Long id;
@Column
String visitorCode;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "visitor_revision_id", referencedColumnName = "visitor_revision_id")
List<VisitorCharacteristic> visitorCharacteristicList;
}
VisitorCharacteristic
public class VisitorCharacteristic {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Column
String attributeCode;
@Column
String attributeValue;
}
JPA will not set VisitorCharacteristic#visitor
field for you, you have to do it manually. If you have some method for adding subsequent VisitorCharacteristic
s, you should add the code for setting visitor in characteristic as well:
public void addVisitorCharacteristic(VisitorCharacteristic visitorCharacteristic) {
if (visitorCharacteristicList == null) {
visitorCharacteristicList = new ArrayList<>();
}
visitorCharacteristic.visitor = this;
visitorCharacteristicList.add(visitorCharacteristic);
}
Here you can find a Gist with your code which works well - look at the line 79.
Without a test case showing the failure its difficult to tell.
Here are some things you can try:
add , nullable = false
to the join column annotation on VisitorCharacteristic
set the relationship in both directions
Visitor v = new Visitor();
VisitorCharacteristic vc = new VisitorCharacteristic();
v.setVisitorCharacteristicList(Arrays.asList(vc));
vc.setVisitor(v);