简体   繁体   中英

Persist entity OneToMany Relationship

I have a probléme when i want to persist 2 objet in database

In Request class:

@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "request") private List documents;

In Document class: @JoinColumn( referencedColumnName = "ID_REQUEST") @ManyToOne Request request

the problem is that when I add request the I find that the 2 object are persisted but in the table Document lD_REQUEST IS ALWAYS NULL

THANK YOU IN ADVANCE and sorry for my English

You need to declare what is the column on the document table that contains the request Id:

@JoinColumn(name = "PARENT_REQUEST")

where PARENT_REQUEST is the name of the column on your Document table

While persisting new data into the database, you've probably added documents to Request's list but forgot to set Request's object to all of your documents on the other side.

Check that you did both things (the following is the example):

Request request = new Request();
//initialization of request
for (...) { //iterate over all document candidates
    Document document = new Document();
    //initialization of document
    document.setRequest(request); //check this!
    request.getDocuments().add(document);
}

Also, it seems that you don't have a not-null constraint on ID_REQUEST column. Add this so you won't have this broken data with nullable ID_REQUEST field in the future (constraint violation exception will be raised instead in this kind of situations).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM