ibatis-user-java mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Johannes Klose <li...@calitrix.de>
Subject Re: ibatis type handler, lazy load?
Date Tue, 01 Jul 2008 17:58:57 GMT
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


Mime
View raw message