1

实体

@javax.persistence.Entity
@javax.persistence.Table(name = "entidade")
public class Entidade {
    private static final long serialVersionUID = -6831078183847196839L;
    @EmbeddedId
    @AttributeOverrides({
            @AttributeOverride(name = "id_titulo", column = @Column(name = "titulo_id", nullable = false)),
            @AttributeOverride(name = "id_empresa", column = @Column(name = "empresa_id", nullable = false)) })
    private PK pk;
//getter//setter
}

//PK

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

    @javax.persistence.Column(name = "id_titulo")
    private Long titulo_id;

    @javax.persistence.Column(name = "id_empresa")
    private Long empresa_id;

        //getter // setter
}

查询正常:如果实例 pk setter

  Criteria criteria = novoCriteria();
    criteria.createAlias("id", "id");
    TituloPK pk = new TituloPK();
    pk.setEmpresa(2L);
    pk.setTitulo(6364L);
    criteria.add(Restrictions.eq("id", pk));
    criteria.list();

查询错误

   Criteria criteria = novoCriteria();
    criteria.createAlias("id", "id");
    criteria.add(Restrictions.eq("id.id_empresa", 2L));
    criteria.list();

控制台错误: *无法解析属性:id_empresa of:Entidade*

只需要按公司搜索,如果我使用约束返回上述错误。

4

1 回答 1

0

In Criteria, as you know, you must use the name of the member of the class, not the name of the field in your database. But the @AttributeOverride annotation is not overriding this attribute in the PK class, but only in the Entidade class. So you must use the name of the attribute as it is declared in your PK class, that is id.empresa_id.

So your code should be:

Criteria criteria = novoCriteria();
    criteria.createAlias("id", "id");
    criteria.add(Restrictions.eq("id.empresa_id", 2L));
    criteria.list();

In one of my project, I could reproduce your error and could solve it using the name of the parameter in the embeddable class. I think it should work for you as well.

于 2013-07-03T19:36:03.337 回答