我正在尝试在 spring mybatis 中设置 ENUM TypeHandlers,出现以下异常,
Cause: org.apache.ibatis.type.TypeException: Unable to find a usable constructor for class com.citi.aw.data.ibatis.KnownTypeHandlers$PortfolioTypeEnum
SQLConfig.xml
<configuration>
<typeHandlers>
<typeHandler javaType="com.citi.aw.entities.portfolio.PortfolioType"
handler="com.citi.aw.data.ibatis.KnownTypeHandlers$PortfolioTypeEnum"/></typeHandlers>
</configuration>
投资组合类型枚举
public enum PortfolioType
{
PROPOSAL,
INVESTABLE,
MODEL,
MODEL_STRATEGY,
STRATEGY,
CLIENT,
FUND_OF_FUND,
REFERENCE,
MODEL_ALLOCATION
}
Class KnownTypeHandlers
public class KnownTypeHandlers
{
public static abstract class PortfolioTypeEnum extends OrdinalEnumTypeHandler
{
public PortfolioTypeEnum()
{
super(PortfolioType.values());
}
}
}
Class OrdinalEnumTypeHandler
public abstract class OrdinalEnumTypeHandler extends org.apache.ibatis.type.BaseTypeHandler<Object>
{
private Object[] enumValues;
protected OrdinalEnumTypeHandler(Object[] enumValues)
{
this.enumValues = enumValues;
}
@Override
public Object getResult(ResultSet rs, String columnName) throws SQLException
{
int intValue = rs.getInt(columnName);
return enumValues[intValue];
}
@Override
public Object getResult(ResultSet rs, int columnPos) throws SQLException
{
int intValue = rs.getInt(columnPos);
return enumValues[intValue];
}
@Override
public Object getResult(CallableStatement arg0, int arg1) throws SQLException
{
throw new SQLException("not implemented");
}
@SuppressWarnings("unchecked")
//@Override
public void setParameter(PreparedStatement ps, int pos, Object parameter, String jdbcType) throws SQLException
{
ps.setInt(pos, ((Enum)parameter).ordinal());
}
//@Override
public Object valueOf(String stringValue)
{
return enumValues[Integer.parseInt(stringValue)];
}
}
最佳答案
我猜你正在使用 MyBatis 3。所以,你不需要为枚举创建任何处理程序。 MyBatis 有一个 typehandler
来处理 Enum 的情况。
搜索 MyBatis 3 Configuration在引用文档中:
typeHandlers
Whenever MyBatis sets a parameter on a PreparedStatement or retrieves a value from a ResultSet, a TypeHandler is used to retrieve the value in a means appropriate to the Java type. The following table describes the default TypeHandlers.
...
EnumTypeHandler - Enumeration Type - VARCHAR any string compatible type, as the code is stored (not index).
然后添加到您的配置 xml(在您的情况下 SqlConfig.xml
:
<!-- mybatis-config.xml -->
<typeHandlers>
<typeHandler handler="org.apache.ibatis.type.EnumTypeHandler"/>
</typeHandlers>
关于java - 无法找到类 Spring Enum Mybatis 异常的可用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39768405/