Hibernate & Locales

Our foos needed to speak different languages.

Java Locales

The following snippet of code yields:

en_CA
fr_CA

import java.util.Locale;

public class LocaleTest {

    public static void main(String[] args) {
        System.out.println(Locale.CANADA);
        System.out.println(Locale.CANADA_FRENCH);
    }
}

Foo Hibernate Mapping

  • Foo.hbm.xml snippet
<hibernate-mapping>

    <class
        name="ca.blah.model.Foo"
        table="FOO"
        mutable="false">

        ...

        <property
            name="locale"
            type="java.util.Locale"
            access="property"
            column="LOCALE" />
    </class>

</hibernate-mapping>

Foo Model Class

  • Foo.java snippet
public class Foo {

    private Locale locale;

    ....

    public Locale getLocale() {
        return this.locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }
}

Foo SQL

  • Most foos are Canadian English, some are Canadian French:
ALTER TABLE FOO
ADD COLUMN LOCALE CHAR(5)
DEFAULT 'en_CA'
NOT NULL;

UPDATE FOO SET LOCALE = 'fr_CA'
WHERE ID IN (2, 4, 6, 8, 11, 38, 60, 61, 70);

Foo DAO Unit Test

  • TestFooDAOImpl.java snippet
import java.util.Locale;

public class TestFooDAOImpl extends DAOTestCase {

    private static final Integer FOO_ID = new Integer(1);

    ...

    public void testGetFoo() {
        Foo foo = ((FooDAO) getDAO()).getFoo(FOO_ID);
        assertFoo(foo, Locale.CANADA);
    }

    private void assertFoo(Foo foo, Locale expectedLocale) {
        assertEquals("foo locale", expectedLocale, foo.getLocale());
    }
}

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply