不同嵌入式中的相同字段

时间:2016-08-10 12:49:35

标签: java hibernate jpa java-ee hibernate-mapping

我有3张桌子A,B,C:

@Embeddable
public class AModel {
    @Column(name = "a_id", insertable = false, updatable = false)
    private int id;
    @Column(name = "a_name")
    private String name;
}

@Embeddable
public class BModel {
    @Column(name = "b_id", insertable = false, updatable = false)
    private int id;
    private int aId;
    @Column(name = "b_name")
    private String name;
}

@Embeddable
public class CModel {
    @Column(name = "c_id", insertable = false, updatable = false)
    private int id;
    private int aId;
    @Column(name = "c_name")
    private String name;
}

我有不可变的实体

@Entity
@Immutable
public class AEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "a_id")
    private int id;

    @Embedded
    private AModel aModel;
    @Embedded
    private BModel bModel;
    @Embedded
    private CModel cModel;
}

我使用EntityManager.createNativeQuery和以下查询创建:

select * from A natural join B natural join C;

但是我得到了一个例外:

org.hibernate.DuplicateMappingException:  Table [aentity] contains physical column name [a_id] represented by different logical column names: [a_id], [aId]

更新:解决方案

将以下注释添加到bModel和cModel可以解决此问题:

@AttributeOverrides({
            @AttributeOverride(name = "aId", column = @Column(name = "a_id", insertable = false, updatable = false))
    })

1 个答案:

答案 0 :(得分:0)

您正在使用@ Id,@ Column和您的可嵌入类AModel。如果要将AModel作为复合键,则可以使用@EmbeddedId。当你在AEntity中定义@Column(name = a_id)以及在可嵌入类AModel中同样的东西时,问题就出现了,所以得到了重复的逻辑映射。