【问题标题】:Hibernate - AttributeOverride default value when using EmbeddedHibernate - 使用 Embedded 时的 AttributeOverride 默认值
【发布时间】:2017-05-29 21:26:28
【问题描述】:

如果在 Hibernate 中使用 @Embedded,如何覆盖 @Column columnDefinition? 更具体地说,有一个例子:

@Embedded
@AttributeOverrides({ @AttributeOverride(name = "isnettogross", column = @Column(name = "isnettogross", columnDefinition="char(1) default 1", nullable = false))})
public ParentGrossNetTransformVariables grossNetTransform;

和类 ParentGrossNetTransformVariables:

@Embeddable
public class ParentGrossNetTransformVariables {
    @Column(name = "isnettogross", columnDefinition="char(1) default 0", nullable = false)
    public boolean isNet2GrossTransform;

当我使用时:

lConf.setProperty("hibernate.hbm2ddl.auto", "update");

数据库中的更改会自动应用。现在我需要在多个实体中添加 ParentGrossNetTransformVariables,但 不同的默认 值为“isnettogross”,以便我尝试使用 @AttributeOverrides 但它不起作用。有什么办法吗?

【问题讨论】:

    标签: java postgresql hibernate


    【解决方案1】:

    我假设“它不起作用”,因为对列名所做的更改没有反映在数据库中。

    hbm2ddl.auto=update 不更新架构。因此,您对列名所做的更改不会反映在数据库中。

    将其更改为 create,以便它根据所做的更改(如果有)重新创建架构。

    更新:

    在可嵌入类中使用insertable=false 属性和columnDefintion,即

    @Column(name = "isnettogross", columnDefinition="char(1) default 0", nullable = false, insertable=false)

    和实体类,

    @AttributeOverrides({ @AttributeOverride(name = "isnettogross", column = @Column(name = "isnettogross", columnDefinition="char(1) default 1", nullable = false, insertable=false))})

    这会忽略触发的 INSERT 语句中感兴趣的列,从而插入配置的默认值。 updatable 也是如此,因此您可能也想根据您的用例使用它。

    最新:

    我很困惑它在您的代码中是如何不起作用的。我已经尝试和测试过;它工作正常。

    我也附上了代码,以防你想看看并交叉验证。

    @Entity
    public class Demo {
    
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;
    
        @Embedded
        @AttributeOverride(name="flag", column=@Column(name="MainFlag", columnDefinition="char(1) default 1", insertable=false))
        private Misc misc;
    
        private Misc misc2;
    
        // Getters and setters
    
    
    
    @Embeddable
    public class Misc {
    
        @Column(name="flag", columnDefinition="char(1) default 0", insertable=false)
        private boolean flag;
    
        // Getters and setters
    

    要测试的代码是一个生成查询的简单 session.save()

    Hibernate: select hibernate_sequence.nextval from dual
    Hibernate: insert into Demo (id) values (?)
    

    附加保存在数据库中的值:D

    【讨论】:

    • 数据库中的“isnettogross”列是新的,当代码执行时,它会创建它。 “它不起作用”意味着“isnettogross”的默认值没有被覆盖并且它保持为 0(查看上面的 ParentGrossNetTransformVariables 类)
    • 更新后的答案应该可以解决您的问题。试一试:)
    • 好的,我花了一些时间,但最后我检查了它,您上面使用的方式的 AttributeOverrides 不会更改实体的默认值。属性“isnettogros”的默认值始终为 false(char (1) 默认为 0),因为它出现在 Embedded 类中。由于我没有找到答案,所以问题仍然存在
    • 添加一个您可以单独测试的示例代码,以确保按预期选择/保留默认值。如果它仍然不起作用,那么我真的想知道为什么! (抱歉命名不好顺便说一句)
    • 我顺便使用了 Oracle DB 来验证这个场景。以防万一,底层数据库架构导致输出不同。
    猜你喜欢
    • 1970-01-01
    • 2017-06-19
    • 2015-01-15
    • 2011-12-24
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 2014-11-30
    相关资源
    最近更新 更多