Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

spring boot - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...