带有多个@Id的Hibernate映射异常

时间:2012-07-09 09:05:29

标签: hibernate annotations

我有两个实体,它们之间有关系。 这是我的第一个实体:

    @Entity
    @Table(name = "APPLICATION_DEVICE")
    public class ApplicationDevice implements Serializable {
    [...]
    @Id
        @ManyToOne
        @JoinColumn(name = "udid", nullable=false)
        public Device getDevice()
        {
            return device;
        }

        public void setDevice(Device device)
        {
            this.device = device;
        }

        @Id
        public Long getApplicationId()
        {
            return applicationId;
        }

        public void setApplicationId(Long applicationId)
        {
            this.applicationId = applicationId;
        }
[...]

请注意,它有一个包含两个字段的主键:applicationId和一个设备(它是另一个关系)。

我的另一个实体是:

@Entity
@Table(name = "SEGMENT_APPLICATION_DEVICES")
public class SegmentApplicationDevice
{
[...]

@Id
    @GeneratedValue
    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    @ManyToOne
    public ApplicationDevice getApplicationDevice()
    {
        return applicationDevice;
    }

    public void setApplicationDevice(ApplicationDevice applicationDevice)
    {
        this.applicationDevice = applicationDevice;
    }

[...]

这是hibernate在尝试映射这些实体时的例外情况:

Exception constructing service 'HibernateSessionSource': Error invoking service builder method org.apache.tapestry5.hibernate.HibernateCoreModule.buildHibernateSessionSource(Logger, List, RegistryShutdownHub) (at HibernateCoreModule.java:123) (for service 'HibernateSessionSource'): Foreign key (FK5B8CB9821C11FEAE:SEGMENT_APPLICATION_DEVICES [applicationDevice_applicationId])) must have same number of columns as the referenced primary key (APPLICATION_DEVICE [udid,applicationId])

我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:1)

ApplicationDevice具有由2列组成的复合ID。然而,ApplicationDevice的manytoone没有指定列(应该有2个),所以使用了一个带有“entityname_id”的列的默认值。

要缓解此问题,请在manytoone中指定两个列,这些列是ApplicationDevice的joincolumns。