hibernate继承映射single_table,其属性为boolean类型

时间:2015-01-26 17:49:50

标签: java hibernate inheritance nullable hibernate-annotations

我的实体有这个层次结构:

TreeItem
LayerItem extends TreeItem
TypicalItem extends TreeItem

TreeItem:

@Entity
@Table(name = "tree_item")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name = "item_type",
    discriminatorType = DiscriminatorType.STRING
)
@DiscriminatorValue("tree_item")
public class TreeItem implements Serializable {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Basic(optional = false)
   private Long id;

   public Long getId() {
     return id;
   }

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

继承类型为SINGLE_TABLE LayerItem有一个属性`已启用'布尔类型。

LayerItem:

 @Entity
@DiscriminatorValue("layer_item")
public class LayerItem extends TreeItem {

   @Column(nullable = true)
   private boolean enabled = false;

   @Column
   private String position;

   @PrePersist
   public void prePersist() {
       if (JUtil.isEmpty(this.enabled)) //We set default value in case if the value is not set yet.
       {
          this.enabled = false;
       }
   }
}

问题在于,当我想要保留TypicalItem(taht没有enabled属性)时,我会遇到此错误:

org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of my.app.entity.LayerItem.enabled

我为它设置了默认值(false),但它没有效果。

1 个答案:

答案 0 :(得分:2)

原始boolean不能是null。因此,您必须将其更改为Boolean对象或使其不可为空:

   @Column(nullable = true)
   private Boolean enabled = false;

或者

   @Column(nullable = false)
   private boolean enabled = false;