简体   繁体   中英

Hibernate not creating back mappings automatically in @OneToMany entity mapping

This is my parent class:

//relevant imports

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Quiz {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(unique = true)
    private Long id;

    private long questionPublished;
    private long questionNeverPublished;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "quiz")
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<Question> questionAnalytics;
}

Child class:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
public class Question {

    private Long questionId;

// the inverse mapped entity was both added and removed and the back mapping didn't work in both cases

    @ManyToOne(fetch = FetchType.EAGER)
    private QuizAnalytics quizAnalytics;

// till here
    @ElementCollection(fetch = FetchType.EAGER)
    @Fetch(value = FetchMode.SUBSELECT)
    private List<Long> attemptedLearners;
}

Now, if I attempt to save the object Quiz with a List of Questions, both objects get persisted, but no mapping between Question and Quiz is created. I am expecting this mapping to be created automatically. If we manually add the mapping before persisting it, the desirable behavior is seen.

However, if we now remove the Quiz from the Question object, and retry the same process, Join tables are created, which is the expected behavior. However, these tables do not get filled. Even if we modify the initial mapping to:

    @OneToMany(cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.FALSE)
    @JoinColumn(name = question_id_join_column)
    private List<QuestionInDepth> questionInDepthAnalytics;

Even in this scenario, the question_id_join_column is not updated.

I am using SpringBoot v2.2.0 and the default hibernate associated with spring-boot-starter-data-jpa

It's because you have defined the mapping wrong. On the parent side you have:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "quiz")

so you're declaring, there is ]a quiz` field in child entity, that holds the joining column, but there is none. You would have to define a mapping for child:

@ManyToOne
@JoinColumn(name = "quiz_id")
private Quiz quiz;

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