Hibernate 4 & the MSSQL Money type

This post covers a situation we ran into where Hibernate 4 wouldn’t map the MS SQL Server Money type to a BigDecimal in our groovy code. Hibernate 3, it turns out, does so just fine, but in our new app, with Hibernate 4 … it just wouldn’t.

The solution we hit on is a bit odd, but it works. First, we had been using a custom UnicodeSQLServerDialect like this:

class UnicodeSQLServerDialect extends SQLServerDialect {
    public UnicodeSQLServerDialect() {
        super()
        registerColumnType(Types.VARCHAR, 255, 'nvarchar($l)')
    }
}

We made an addition to the dialect in order to handle the money type, but then ran into an issue where the decimal type started being mapped as if it’s money. What we ended up with is this:

class UnicodeSQLServerDialect extends SQLServerDialect {
    public UnicodeSQLServerDialect() {
        super()
        registerColumnType(Types.VARCHAR, 255, 'nvarchar($l)')
        registerColumnType(Types.NUMERIC, 254, 'decimal($p, $s)')
        registerColumnType(Types.NUMERIC, 255, 'money')
    }
}

and some changes to our domain classes which are odd, but work. Namely, if an entry is a decimal in the db, we specify a length=254, and if it’s money, we specify a length=255.

    @Column(name = 'Quantity', length=254) // Map to decimal(?,?)
    BigDecimal quantity

    @Column(name = 'Price', length=255) // Maps to money
    BigDecimal price

It’s really strange, but digging through the hibernate code, it looks like the mapping of types relies heavily on the length.

Strange … confusing … but it works.

Advertisements

About John Woodward

Principal Consultant at Improving Enterprises, Inc.
This entry was posted in Software and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s