Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA @OneToMany : foreign key is null

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 visitorCharacteristic table.

I would like to join the 2 tables with the "visitor_revision_id"

@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
@ToString
public class Visitor {
    @Id
    @Column(name="visitor_revision_id")
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    Long id;

    String visitorCode;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "visitor")
    List<VisitorCharacteristic> visitorCharacteristicList;
}

@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
@ToString
class VisitorCharacteristic {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    Long id;

    @JoinColumn(name = "visitor_revision_id")
    @ManyToOne(optional = false) //fetch = FetchType.EAGER, cascade =  CascadeType.ALL)
    Visitor visitor;

    @Column(nullable = false)
    String attributeCode;

    @Column(nullable = false)
    String attributeValue;    
}

Thanks in advance for your help

like image 914
GeorgesD Avatar asked Dec 05 '16 15:12

GeorgesD


2 Answers

JPA will not set VisitorCharacteristic#visitor field for you, you have to do it manually. If you have some method for adding subsequent VisitorCharacteristics, 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.

like image 130
Maciej Dobrowolski Avatar answered Oct 13 '22 09:10

Maciej Dobrowolski


Without a test case showing the failure its difficult to tell.

Here are some things you can try:

  1. add , nullable = false to the join column annotation on VisitorCharacteristic

  2. set the relationship in both directions Visitor v = new Visitor(); VisitorCharacteristic vc = new VisitorCharacteristic(); v.setVisitorCharacteristicList(Arrays.asList(vc)); vc.setVisitor(v);

like image 1
Bob Lukens Avatar answered Oct 13 '22 09:10

Bob Lukens