Custom types using org.hibernate.usertype.UserType by R4R Team

When we talk about the hibernate mapping type then we found the another type in this approach we lean about the  use of the  org.hibernate.usertype.UserType interface, which presents a somewhat simplified view of the org.hibernate.type.Type interface. Using a org.hibernate.usertype.UserType, our HibernateMapping is the class that can look like the given code:

Example: Defining the custom UserType

public class HibernateMapping implements UserType 
{
    public int[] sqlTypes() 
       {
        return new int[] {
                BigDecimalType.INSTANCE.sqlType(),
                CurrencyType.INSTANCE.sqlType(),
        };
    }

    public Class getReturnedClass() {
        return HibernateMapping.class;
    }

    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException {
        assert names.length == 2;
        BigDecimal amount = BigDecimalType.INSTANCE.get( names[0] ); // already handles null check
        Currency currency = CurrencyType.INSTANCE.get( names[1] ); // already handles null check
        return amount == null && currency == null
                ? null
                : new Money( amount, currency );
    }

    public void nullSafeSet(PreparedStatement st, Object value, int index) throws SQLException {
        if ( value == null ) {
            BigDecimalType.INSTANCE.set( st, null, index );
            CurrencyType.INSTANCE.set( st, null, index+1 );
        }
        else {
            final Money money = (Money) value;
            BigDecimalType.INSTANCE.set( st, money.getAmount(), index );
            CurrencyType.INSTANCE.set( st, money.getCurrency(), index+1 );
        }
    }

    ...
}

As we see there is not much difference between the org.hibernate.type.Type example and the org.hibernate.usertype.UserType.

Example, but that is only because of the snippets shown. Choose the org.hibernate.type.Type approach there are quite a few more methods you would need to implement as compared to the org.hibernate.usertype.UserType.

We have to remember always Both org.hibernate.usertype.UserType and org.hibernate.usertype.CompositeUserType originally added to isolate user code from internal changes to the org.hibernate.type.Type interfaces.
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!