如何使用JPA / Hibernate将int2数据库字段用作Java中的布尔值

时间:2010-05-10 08:37:44

标签: java hibernate jpa

我使用JPA和Hibernate编写了一个基于已有数据库(postgreSQL)的应用程序。表中有一个int2列(activeYN),用作布尔值(0 => false(非活动),而不是0 => true(活动))。在Java应用程序中,我想将此属性用作布尔值。所以我定义了这样的属性:

@Entity
public class ModelClass implements Serializable {    
  /*..... some Code .... */
  private boolean active; 

  @Column(name="activeYN")
  public boolean isActive() {
    return this.active; 
  }
 /* .... some other Code ... */

}

但是有一个例外,因为Hibernate需要一个布尔数据库字段而不是int2。 我可以在java中使用布尔值时以任何方式进行映射吗?

我有一个可能的解决方案,但我真的不喜欢它: 我的“hacky”解决方案如下:

@Entity
public class ModelClass implements Serializable {    
  /*..... some Code .... */
  private short active_USED_BY_JPA; //short because i need int2

  /**
   * @Deprecated this method is only used by JPA. Use the method isActive()
   */
  @Column(name="activeYN")
  public short getActive_USED_BY_JPA() {
    return this.active_USED_BY_JPA;
  }

  /**
   * @Deprecated this method is only used by JPA. 
   * Use the method setActive(boolean active)
   */
  public void setActive_USED_BY_JPA(short active) {
    this.active_USED_BY_JPA = active; 
  }

  @Transient //jpa will ignore transient marked methods
  public boolean isActive() {
    return getActive_USED_BY_JPA() != 0; 
  }

  @Transient
  public void setActive(boolean active) {
    this.setActive_USED_BY_JPA = active ? -1 : 0;
  }

 /* .... some other Code ... */

}

此问题还有其他解决方案吗?

hibernate配置中的“hibernate.hbm2ddl.auto”-value设置为“validate”。

(对不起,我的英语不是最好的,我希望你能理解它)..

3 个答案:

答案 0 :(得分:1)

嗯,问题是int2用于存储签名的双字节整数,无论你如何使用它,Hibernate都不知道你的逻辑来翻译值在Java级别的boolean

所以你必须使用你的hacky解决方案(即阅读int2中的short列并在你的实体中转换它),你可以通过移动注释使事情变得更加性感属性:

@Entity
public class ModelClass implements Serializable {    
  /*..... some Code .... */

  @Column(name="activeYN")
  private short active; 

  public boolean isActive() {
    return this.active!=0; 
  }
 /* .... some other Code ... */

}

或者,如果使用JPA扩展名不是问题(JPA不支持自定义类型),请使用您使用custom type注释声明的@Type

@Entity
public class ModelClass implements Serializable {    
  /*..... some Code .... */
  private boolean active; 


  @org.hibernate.annotations.Type(type = "my.package.ShortToBooleanUserType")
  @Column(name="activeYN")
  public boolean isActive() {
    return this.active; 
  }
 /* .... some other Code ... */

}

ShortToBooleanUserType是一个实现org.hibernate.UserTypeorg.hibernate.CompositeUserType的类(请参阅文档)并在两个方向进行转换。

答案 1 :(得分:1)

您也可以尝试使用特定于Hibernate的注释:

@Type(type = "numeric_boolean")

答案 2 :(得分:0)

解决方案是使用custom value type