How to use a int2 database-field as a boolean in Java using JPA/Hibernate

Posted by mg on Stack Overflow See other posts from Stack Overflow or by mg
Published on 2010-05-10T08:37:43Z Indexed on 2010/05/10 8:44 UTC
Read the original article Hit count: 341

Filed under:
|
|

Hello...

I write an application based on an already existing database (postgreSQL) using JPA and Hibernate. There is a int2-column (activeYN) in a table, which is used as a boolean (0 => false (inactive), not 0 => true (active)). In the Java application i want to use this attribute as a boolean. So i defined the attribute like this:

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

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

}

But there ist an exception because Hibernate expects an boolean database-field and not an int2. Can i do this mapping i any way while using a boolean in java??

I have a possible solution for this, but i don't really like it: My "hacky"-solution is the following:

@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 ... */

}

Are there any other solutions for this problem?

The "hibernate.hbm2ddl.auto"-value in the hibernate configuration is set to "validate".

(sorry, my english is not the best, i hope you understand it anyway)..

© Stack Overflow or respective owner

Related posts about java

Related posts about jpa