父类在Hibernate中多次获取

时间:2012-08-20 06:08:25

标签: java spring hibernate

我有两个使用OneToMany映射的类。 有一个Question类和一个Answer类。对于每个问题,表中都有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();
    }

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分: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以避免获取cartezian产品。