Hi Nathan,
Here follows some sample code I use in my development. Please note that I do
not have an abstract safe enum class from which the actual enum derives (I
don't need: I have exactly ONE enum in my project currently!). So depending
on your own implementation of the safe enum pattern you might need to adapt
the following code.
Here is the enum class sample first:
public final class AccountRole
{
public static final int _ROLE_BASIC = 0;
public static final int _ROLE_INITIATOR = 1;
public static final AccountRole ROLE_BASIC =
new AccountRole(_ROLE_BASIC);
public static final AccountRole ROLE_INITIATOR =
new AccountRole(_ROLE_INITIATOR);
public int getValue()
{
return _value;
}
public static AccountRole get(int value)
{
switch (value)
{
case _ROLE_BASIC: return ROLE_BASIC;
case _ROLE_INITIATOR: return ROLE_INITIATOR;
default: return null;
}
}
private AccountRole(int value)
{
_value = value;
}
Object readResolve() throws ObjectStreamException
{
return get(getValue());
}
final private int _value;
}
Then the iBATIS TypeHandler for it:
public class AccountRoleTypeHandler implements TypeHandlerCallback
{
public Object getResult(ResultGetter getter)
throws SQLException
{
if (getter.wasNull())
return null;
return AccountRole.get(getter.getInt());
}
public void setParameter(ParameterSetter setter, Object parameter)
throws SQLException
{
if (parameter == null)
{
setter.setNull(Types.INTEGER);
}
else
{
AccountRole role = (AccountRole) parameter;
setter.setInt(role.getValue());
}
}
public Object valueOf(String s)
{
return s;
}
}
Please note that I did not do anything special in the valueOf() method
because I do not care about null values (honestly I did not clearly
understand concrete use cases of that method).
And finally the TypeHandler declaration in the sqlmap config file:
<typeHandler javaType="net.sourceforge.hivetranse.AccountRole"
callback="net.sourceforge.hivetranse.dao.AccountRoleTypeHandler"/>
It works correctly for me. Please note that I did not have to change any
statement or result-map declaration to make it work, the type handler has
been used transparently by iBATIS.
Certainly, there must be some way to generalize the code if you use a
generic safe enum library.
Hope this helps
Jean-Francois
-----Original Message-----
From: Nathan Maves [mailto:[EMAIL PROTECTED]
Sent: Friday, December 24, 2004 12:27 AM
To: [email protected]
Subject: Different twist on complex properities
Team,
I was curious if anyone has used a Type Safe Enumeration as a complex
property of a class.
I have a class Report that needs to have a property named Frequency.
In the database this is stored as a number. (1-daily, 2-weekly ...)
But I would like to use a Type Safe Enumeration for this attribute in
the class. If anyone has any good ideas on how to accomplish this
please let me know.
Nathan