创建可通过引用实体过滤的休眠条件

问题描述 投票:1回答:1

我有一个实体(PersonQuestionsEntity),其具有一个PersonEntity和QuestionEntity作为其主键。我使用组合键来反映这种关系。

现在,我想创建一个可以执行以下操作的Criteria对象:查找给定QuestionId和一个人的年龄的所有PersonQuestion实体。

这是我为此创建条件的尝试:

    Session session = getHibernateTemplate().getSessionFactory().openSession();
    Criteria criteria = session.createCriteria(PersonQuestionsEntity.class);
    criteria.add(Restrictions.eq("question.questionId", "87"));
    criteria = criteria.createCriteria("person");
    criteria.add(Restrictions.eq("age", 23));
    criteria.setMaxResults(100);
    List l = criteria.list();

问题是我收到此错误:

Caused by: java.sql.SQLException: ORA-00904: "PERSONENTI1_"."AGE": invalid identifier

在生成的SQL中,似乎该人被称为PERSONENTI4,而不是PERSONENTI1。如果我复制SQL并使用PERSONENTIT4而不是PERSONENTI4运行它,则它可以工作(某种程度上-似乎在进行某种笛卡尔联接)。

关于我可能做错了什么的线索?我对使用Hibernate非常陌生。

PersonQuestionsEntity

@Entity
@IdClass(com.anonymous.model.PersonQuestionsKey.class)
@Table(name = "PERSON_QUESTIONS")
public class PersonQuestionsEntity implements Serializable
{
    private static final long serialVersionUID = -8254277382097937813L;

    @Id
    @ManyToOne
    @JoinColumn(name = "USER_NAME", nullable = false)
    private PersonEntity person;

    @Id
    @ManyToOne
    @JoinColumn(name = "QUESTION_ID", nullable = false)
    private QuestionEntity question;

    @Column(name = "THEIR_ANSWER")
    private int theirAnswer;
}

PersonEntity

@Entity
@Table(name = "PERSON")

public class PersonEntity implements Serializable
{
    private static final long serialVersionUID = -1699435979266209440L;

    @Id
    @Column(name = "USER_NAME", length = 20, nullable = false)
    private String userName;

    @Column(name = "USER_NAME_REAL", length = 20, nullable = false)
    private String userNameReal;

    @Column(name = "AGE", nullable = false)
    private int age;
}

PersonQuestionsKey

   @Embeddable
    public class PersonQuestionsKey implements Serializable
    {
        private static final long serialVersionUID = -264160855961369405L;

        @Id
        @ManyToOne
        @JoinColumn(name = "USER_NAME", nullable = false)
        private PersonEntity person;

        @Id
        @ManyToOne
        @JoinColumn(name = "QUESTION_ID", nullable = false)
        private QuestionEntity question;

}
java hibernate persistence criteria
1个回答
0
投票

首先,您实际上并不需要内部标准,只需使用:

条件标准= session.createCriteria(PersonQuestionsEntity.class);条件.add(Restrictions.eq(“ question.questionId”,“ 87”));条件.add(Restrictions.eq(“ person.age”,23));条件.setMaxResults(100);清单l =条件.list();

第二(关于联接类型),在这种情况下,我通常会使用产生内部联接的HQL。 HQL可能如下所示:

来自PersonQeustionEntity,其中question.questionId =:questionId和person.age =:age

在结果Query对象中,可以将参数questionIdage设置为所需的输入。

© www.soinside.com 2019 - 2024. All rights reserved.