Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean true value in Hibernate

Is it possible to set the hibernate to save -1 instead of 1 as true value for a Boolean field in the database? I need -1 to maintain compatibility with other program made in Delphi.

like image 636
sammubr Avatar asked Jun 20 '15 22:06

sammubr


2 Answers

@Type(type="com.sample.type.CustomClass")
@Column(name = "TEST_FLAG")
private boolean testFlag;

The @Type annotation needs a full path to the class that implements the userType interface; this is the factory for producing the target type of the mapped column

CustomClas.java which implements UserType interface provided by hibernate

UserType implementation provides developer to hook the custom logic/implementation and acts as a adapter between relational database and your class property.

You need to write the conversion logic in following methods.

  • nullSafeGet() : Creates the custom object from the data returned by the result set
  • nullSafeSet() : Converts custom object into value which needs to be passed to prepared statement

Check the API for detail on the hibernate site.

like image 121
027 Avatar answered Sep 19 '22 12:09

027


Why not use Integer instead of Boolean?

Integer value;
public void setValue(Boolean b) {
    this.value = (b != null ? (b ? -1 : 0) : null);
}
public Boolean getValue() {
    return (this.value != null ? (this.value == -1 ? true : false) : null);
}
like image 40
Krzysiek Avatar answered Sep 19 '22 12:09

Krzysiek