hibernate and mappedBy: Is it possible to automatically set foreign key without setting bidirectional relationship among objects?

前端 未结 1 1546
隐瞒了意图╮
隐瞒了意图╮ 2021-01-27 02:19

Welcome,

I have 2 classes: Conversation and Question. One Conversation have many questions.

Conversation.java:

package com.jcg.jpa.mappedBy;

imp         


        
相关标签:
1条回答
  • so hibernate should know what is conversation foreign key for these two questions (because they are located on specified conversation questions list).

    No Hibernate shouldn't know what is the Conversation of these two Questions if you don't specify it using setConversation(), because it's dealing with objects here, and these two questions doesn't have any indication on which Conversation they are part of.

    Explanation:

    Because when you only add these two questions to the Conversation object, this information won't be visible in the Questions objects.

    Another thing here, the mappedBy attribute is indicating wich object is the owner of the mapping, so how can the mapping be made if there's no given object in the mappedBy side?

    That's why you should specify the Conversation in Question object, so the mapping can be correctly evaluated by Hibernate.

    Note:

    It's recommended to use a Set for OneToMany mapping rather than any other Collection, because this collection shouldn't have any duplicates, so you better change it to:

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="conversation")
    private Set<Question> questions = new HashSet<Question>();
    
    0 讨论(0)
提交回复
热议问题