Hibernate隐式连接的奇怪问题

时间:2013-02-11 18:26:34

标签: hibernate hql

我从Hibernate 4.1.9收到一个奇怪的错误。这是我的实体类结构:

@Entity
@Table( name = "security_grant", catalog = "security")
public class SecurityGrantDO implements Serializable
{
    private long id;
    private SecuritySubjectDO securitySubject;
    @Id
    @GeneratedValue( strategy = IDENTITY )
    @Column( name = "id", unique = true, nullable = false )
    public long getId()
    {
        return this.id;
    }
    public void setId( long id )
    {
        this.id = id;
    }
    @Column( name = "security_subject__id", nullable = false )
    public SecuritySubjectDO getSecuritySubject()
    {
        return securitySubject;
    }
    public void setSecuritySubject( SecuritySubjectDO securitySubject )
    {
        this.securitySubject = securitySubject;
    }
}

@Entity
@Table( name = "security_subject", catalog = "security")
public class SecuritySubjectDO implements Serializable
{
    private long id;
    private ObjectType domainObjectType;
    private long domainObjectId;
    @Id
    @GeneratedValue( strategy = IDENTITY )
    @Column( name = "id", unique = true, nullable = false )
    public long getId()
    {
        return this.id;
    }
    public void setId( long id )
    {
        this.id = id;
    }
    @Column( name = "domain_object_type", nullable = false )
    @Enumerated(EnumType.STRING)
    public ObjectType getDomainObjectType()
    {
        return domainObjectType;
    }
    public void setDomainObjectType( ObjectType domainObjectType )
    {
        this.domainObjectType = domainObjectType;
    }
    @Column( name = "domain_object__id", nullable = false)
    public long getDomainObjectId()
    {
        return domainObjectId;
    }
    public void setDomainObjectId( long domainObjectId )
    {
        this.domainObjectId = domainObjectId;
    }
}

这是我的问题:

Query query = session.createQuery( "from SecurityGrantDO g where g.securitySubject.domainObjectId = :doid and " +
            "g.securitySubject.domainObjectType = :dot" );

执行此操作时,Hibernate会抛出:

org.hibernate.QueryException:无法解析属性:domainObjectId:com.jelli.phoenix.model.security.SecurityGrantDO [来自com.jelli.phoenix.model.security.SecurityGrantDO g其中g.securitySubject.domainObjectId =: doid和g.securitySubject.domainObjectType =:dot]

咦? domainObjectId不是SecurityGrantDO的属性;它是SecuritySubjectDO的一个属性。我认为消息本身可能只是一个错误,但为什么隐式连接失败?

1 个答案:

答案 0 :(得分:2)

没有关系从SecurityGrantDO映射到SecuritySubjectDO。使用以下映射:

@Column( name = "security_subject__id", nullable = false )
public SecuritySubjectDO getSecuritySubject()

Hibernate尝试将其视为SecurityGrantDO的Serializable持久属性,并感到困惑。如果需要这两个实体之间的关系,可以采用以下方法:

@ManyToOne //or @OneToOne, depends about preferred domain model
@JoinColumn( name = "security_subject__id", nullable = false )
public SecuritySubjectDO getSecuritySubject() {
    return securitySubject;
}