Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hibernate

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.

like image 761
Holger Pappenstiel Avatar asked Nov 23 '12 13:11

Holger Pappenstiel


2 Answers

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

like image 123
JB Nizet Avatar answered Oct 22 '22 20:10

JB Nizet


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.

like image 27
dkateros Avatar answered Oct 22 '22 19:10

dkateros