【问题标题】:Remove redundant column for composite key in Hibernate在 Hibernate 中删除复合键的冗余列
【发布时间】:2016-07-08 08:04:26
【问题描述】:

Hibernate 会创建空的“ID”列,以防出现本文中的代码。

如何调整它以不创建“ID”列(“ID”是已创建列的确切名称)或无法更改?

    @Entity
    @Table(name = "CATEGORY_RELATIONS")
    public class CategoryRelations implements Serializable {
    private CategoryRelationsPrimaryKey id;
    @Id
    @Column(name = "CATEGORY_RELATIONS_CATEGORY_ID")
    private String categoryId;
    @Id
    @Column(name = "CATEGORY_RELATIONS_PARENT_ID")
    private String parentId;
    //getters and setters
    @Entity
    @IdClass(CategoryRelationsPrimaryKey.class)
    public class CategoryRelationsPrimaryKey implements Serializable {
        protected long categoryId;
        protected long parentId;
        //euqals, hashCode
    }
}

【问题讨论】:

    标签: java sql hibernate orm annotations


    【解决方案1】:

    1) @IdClass 应该位于实体,而不是复合 id 类;

    2) 如果您已经用@Id 标记了id 属性,则不需要单独的id 属性:

    @Entity
    @Table(name = "CATEGORY_RELATIONS")
    @IdClass(CategoryRelationsPrimaryKey.class)
    public class CategoryRelations implements Serializable {
    
        @Id
        @Column(name = "CATEGORY_RELATIONS_CATEGORY_ID")
        private String categoryId;
    
        @Id
        @Column(name = "CATEGORY_RELATIONS_PARENT_ID")
        private String parentId;
    
        //...
    
    }
    
    public class CategoryRelationsPrimaryKey implements Serializable {
        protected String categoryId;
        protected String parentId;
        // ...
    }
    

    如果您需要一些名为id 的属性,请将其设为transient 以避免映射到数据库表列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 2021-01-22
      相关资源
      最近更新 更多