Holger Pappenstiel
Holger Pappenstiel

Reputation: 139

Hibernate: Changing Boolean-Mapping to 's'/'n'?

I'm currently trying to get Hibernate working with an Oracle 8 Legacy-Database. Everything's working fine so far but now I've hit a problem I have yet to overcome: Boolean Values in the database are not kept in the 'y'/'n' or 't'/'f' or 0/1 format but because the project is from the spanish-speaking area it is saved as 's'/'n' for si/no. However, this is obviously not supported by Hibernate.

Any ideas? I would be thankful for every little pointer in the right direction. For example which class does the Boolean-Mapping, so I could maybe override it/create my own version of it?

Thanks in advance.

Upvotes: 6

Views: 1674

Answers (3)

dkateros
dkateros

Reputation: 1594

Another extension point I am aware of is to use the contract

org.hibernate.usertype.UserType

The more significant methods you need to implement are nullSafeSet and nullSafeGet. These provide the necessary hooks to convert the value from the ResultSet to the java object before Hibernate "hydrates" the object and vice-versa.

For example

public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
        String value = rs.getString(names[0]);
        if(value==null) {
             //handle this
        }
        //handle other possibilities like Si/No or whatever here
        return "s".equals(value) ? Boolean.TRUE : Boolean.FALSE;
    }

    public void nullSafeSet(PreparedStatement st, Object value, int index) 
    throws HibernateException, SQLException {
        if (value==null) {
            //handle this
            return;
        }
        Boolean bValue = (Boolean) value;
        if(bValue) {
            st.setString("s", index);
        } else {
            st.setString("n", index);
        }
        //handle other possibilities like Si/No or whatever here
    }

Then it is a simple matter of making your UserType implementation known to Hibernate, which you can do in the hibernate mappings as a typedef element or simply using the type attribute of the property elements the UserType is applicable to.

Upvotes: 2

harrybvp
harrybvp

Reputation: 2505

This is how i would do by defining a custom Type in Hibernate

public class CustomBooleanType extends BooleanType {

   public static final String TRUE = "s";
   public static final String FALSE = "n";

   public CustomBooleanType () {
      super(CharTypeDescriptor.INSTANCE, new BooleanTypeDescriptor(TRUE.charAt(0), FALSE.charAt(0)));
   }  
}

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691625

AFAIK, you would have to use your own Dialect class, extending the Dialect class you're currently using, and override the method toBooleanValueString().

Upvotes: 2

Related Questions