1

我有 2 个具有 OneToMany 映射的类。有一个问题类和一个答案类。对于每个问题,表中都有 4 个答案。表格中有 10 个问题行和相应的 40 个答案行现在,当我尝试获取列表时,它给了我 40 个问题而不是 10 个问题,每个问题有 4 个重复。

这是我的问题课:

@Entity
@Table(name = "QUESTIONS")
public class Question implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "QUES_ID_SEQ")
    @SequenceGenerator(name = "QUES_ID_SEQ", sequenceName = "QUES_ID_SEQ")
    @Column(name = "QUESTION_ID")
    private Long id;

    @Column(length = 255)
    private String question;

    @OneToMany(targetEntity = Answer.class, fetch = FetchType.EAGER)
    @Cascade(CascadeType.SAVE_UPDATE)
    @JoinTable(name = "QNA",
                joinColumns = @JoinColumn(name = "QUESTION_ID"),
                inverseJoinColumns = @JoinColumn(name = "ANSWER_ID", referencedColumnName = "ANSWER_ID"))
    private List<Answer> answers;

    public Question() {}

// getters and setters ...
}

这是我的答案类:

@Entity
@Table(name = "ANSWERS")
public class Answer implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ANS_ID_SEQ")
    @SequenceGenerator(name = "ANS_ID_SEQ", sequenceName = "ANS_ID_SEQ")
    @Column(name = "ANSWER_ID")
    private Long id;

    @Column(length = 255)
    private String answer;

    private boolean correct;

    public Answer() {}

// getters and setters ...
}

我正在获取这样的问题:

    @Transactional
    public List<Question> retrieveQuestions(){
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Question.class);
        return (List<Question>) criteria.list();
    }
4

2 回答 2

3

另外,我使用以下代码解决了这个问题:

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Question.class);
        return (List<Question>) criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

Criteria.DISTINCT_ROOT_ENTITY <- 这段代码帮助我获得独特的问题,而且我使用了 FetchType.EAGER。它工作得很好。

于 2012-08-20T07:57:55.873 回答
0

您的映射不正确。如果你有从问题到回答的一对多关联,为什么你有一个连接表?

这个一对多关联的正确映射是:

在回答课上:

@ManyToOne
@JoinColumn(name = "question_id")
public Question getQuestion() {
    return question;
}

关于问题类:

@OneToMany(mappedBy = "question", fetch = FetchType.EAGER)
public List<Answer> getAnswer() {
    return answers;
}

还有一件事:对于 Question 类中的一个集合映射,可以使用 FetchType.EAGER,但是如果您将另一个集合开关映射到 FetchType.LAZY 以避免获取笛卡尔积。

于 2012-08-20T07:01:51.000 回答