Hibernate双级标准

时间:2016-05-12 17:38:32

标签: java hibernate

我有两节课。

Occupation.class

@Entity
@Table(name = "occupazione")
public class Occupazione implements java.io.Serializable {

    /**
     * omitted the fields for brevity
     */

    private int idOccupation;
    private Posto posto;

@ManyToOne
    @JoinColumn(name = "id_posto")
    public Posto getPosto() {
        return this.posto;
    }

    public void setPosto(Posto posto) {
        this.posto = posto;
    }

和Posto.class

@Entity
@Table(name = "posti")
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="idPosto")
public class Posto implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private int idPosto;
    private Piano piano;


    @ManyToOne
    @JoinColumn(name="id_piano")
    @JsonIgnore
    public Piano getPiano() {
        return piano;
    }

    public void setPiano(Piano piano) {
        this.piano = piano;
    }

现在,我想要检索给定钢琴的所有职业对象

我是这样做的

Criteria criteria = sess.getSession().createCriteria(Occupation.class).
                            createCriteria("posto").
        add(Restrictions.eq("piano", piano));

        return criteria.list();

但是我得到了这个例外

org.hibernate.QueryException: could not resolve property: posto of: it.besmart.models.Posto

但它很奇怪,因为posto应该被称为职业,而不是Posto本身......

2 个答案:

答案 0 :(得分:0)

更改您的代码

Criteria criteria = sess.getSession().createCriteria(Occupation.class).
                            createCriteria("posto").
        add(Restrictions.eq("piano", piano));

Criteria criteria = sess.getSession().createCriteria(Occupation.class).
        add(Restrictions.eq("piano", piano));

希望它会有所帮助。

答案 1 :(得分:0)

我终于设法解决了它,用createAlias ...

很容易
Criteria criteria = sess.getSession().createCriteria(Occupation.class).
                            createAlias("posto", "p").
        add(Restrictions.eq("p.piano", piano));