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)..
Well, the problem is that
int2is used store signed two-byte integer, regardless of how you use it and Hibernate doesn’t have any knowledge of your logic to translate the value into abooleanat the Java level.So you’ll have to use your hacky solution (i.e. read the
int2column in ashortand convert it in your entity) that you could maybe make things a bit sexier by moving annotations on attributes:Or, if using a JPA extension is not a problem (JPA dosen’t support custom types), use a custom type that you declare with the
@Typeannotation:Where
ShortToBooleanUserTypeis a class that implements eitherorg.hibernate.UserTypeororg.hibernate.CompositeUserType(refer to the documentation) and does the conversion in both direction.