简体   繁体   English

如何在休眠实体中初始化复杂类型

[英]How to initialise a complex type in hibernate entity

A member of my class is of Type Byte.我班的一个成员是字节类型。 As you know its initial value would be NULL .如您所知,它的初始值是NULL But I want it to be 0 if no one calls constructor by default.但如果默认情况下没有人调用构造函数,我希望它为0 So would the way I do it be the right way?那么我这样做的方式是正确的吗? Because in my database this value is not allowed to be NULL .因为在我的数据库中,这个值不允许为NULL So I need to give it a value which by default should be 0 .所以我需要给它一个默认值应该是0

@Entity
@Table(name = "Holiday")
public class Holiday {

   @Column(columnDefinition = "Bit(2)")
   private Byte approved = (byte) 0;

   public Holiday() {
   }

   public Holiday( Byte approved) {
      super();
      this.approved = approved;
   }

PS: Of course this class has many more members and also another constructor. PS:当然这个类有更多的成员和另一个构造函数。 But for demo I removed all the other members.但是对于演示,我删除了所有其他成员。

Try to add nullable = false :尝试添加nullable = false

    @Entity
    @Table(name = "Holiday")
    public class Holiday {

        @Column(columnDefinition = "Bit(2)", nullable = false)
        private Byte approved = (byte) 0;

        public Holiday() {
        }

        public Holiday( Byte approved) {
            super();
            this.approved = approved;
        }

Or add in columnDefinition NOT NULL DEFAULT 0或添加 columnDefinition NOT NULL DEFAULT 0

 @Column(columnDefinition = "Bit(2) NOT NULL DEFAULT 0")

So would the way I do it be the right way?那么我这样做的方式是正确的吗?

Yes, it's right way.是的,方法是对的。 You can see a lot of similar examples in the hibernate documentation (especially for collections).你可以在 hibernate 文档中看到很多类似的例子(尤其是集合)。 I would suggest you to put this initialization in the default constructor and, if you have other constructors, call this constructor from them.我建议您将此初始化放在默认构造函数中,如果您有其他构造函数,请从它们调用此构造函数。

@Entity
@Table(name = "Holiday")
public class Holiday {

   @Column(columnDefinition = "Bit(2)")
   private Byte approved;

   public Holiday() {
      this.approved = 0;
      // other default initialization
   }

   public Holiday(Byte approved) {
      this();
      this.approved = approved;
   }
   // ...
}

Since you already use columnDefinition , you can define the default value there:由于您已经使用columnDefinition ,您可以在那里定义默认值:

columnDefinition = "Bit(2) NOT NULL DEFAULT 0" . columnDefinition = "Bit(2) NOT NULL DEFAULT 0" This will set the constraint on the database level while rejecting NULL values.这将在拒绝 NULL 值的同时设置数据库级别的约束。

If you would rather do it on the application level you can set it on the field instead, that's perfectly fine for default values.如果您更愿意在应用程序级别执行此操作,则可以改为在字段上进行设置,这对于默认值来说完全没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM