You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user-java@ibatis.apache.org by Josh Joy <jo...@gmail.com> on 2008/07/01 19:25:41 UTC

ibatis type handler, lazy load?

Hi,

Ok, I'll best to explain what I'm doing and maybe if someone can help
provide some suggestions or paths to explore...

We have various Java enums in our application, and on the database side
these enums are mapped to primary ids on the database.

For example, we can do something like Status.ACTIVE which on the db would
map to primary id 1.

In our code we want to use Status.ACTIVE everywhere, and then write a type
handler that when it comes time to interact with the database it converts it
to 1, and converts 1 to Status.ACTIVE.

The issue is that we don't want to hard code these ids in our type handler,
want to pull these ids from the database into some lookup map, which then
the typehandler can use to do the proper conversions.

So the issue is that there is a circular dependency, we rely on ibatis to
connect to the database, though the type handler itself needs a call to the
database to get the mappings of the enums to primary ids.

How have other people handled this?

Also we are using spring with ibatis.

Thanks,
Josh

Re: ibatis type handler, lazy load?

Posted by Johannes Klose <li...@calitrix.de>.
Hi,

to convert an database id to the proper enum instance, you can write a
small factory method in the enum class. Also, every enum gets it's
database id.

enum MyType
{
	FOO(1), BAR(2), BAZ(3);
	private int id = 0;
	public MyType(int id) { this.id = id; }
	public int getId() { return id; }
	public static MyType getInstance(int id)
	{
		switch(id) {
			case 1: return FOO;
			case 2: return BAR;
			case 3: return BAZ;
		}
		throw new IllegalArgumentException("Invalid enum id");
	}
}

Writing a type handler for this is very easy:

// Imports...
public class MyTypeHandler implements TypeHandlerCallback
{
	public Object getResult(ResultGetter getter) throws SQLException
	{
		int value = getter.getInt();
		if (getter.wasNull()) {
			return null;
		}
		return MyType.getInstance(value);
	}

	public void setParameter(ParameterSetter setter, Object parameter)
			throws SQLException
	{
		if (parameter == null) {
			setter.setNull(Types.INTEGER);
		} else {
			MyType foo = (MyType) parameter;
			setter.setInt(foo.getId());
		}
	}

	public Object valueOf(String s)
	{
		return s;
	}
}

That's how i'm doing this. 

Regards,

Johannes