您可以使用自定义 TypeHandler 将结果直接转换为 ENUM,这样您就不需要在数据库中将所有值作为大写 ENUM 名称存储。
这是您的状态枚举自定义处理程序的外观。
public class StatusTypeHandler implements TypeHandler<Status> {
public Status getResult(ResultSet rs, String param) throws SQLException {
return Status.getEnum(rs.getInt(param));
}
public Status getResult(CallableStatement cs, int col) throws SQLException {
return Status.getEnum(cs.getInt(col));
}
public void setParameter(PreparedStatement ps, int paramInt, Status paramType, JdbcType jdbctype)
throws SQLException {
ps.setInt(paramInt, paramType.getId());
}
}
通过添加以下代码在 mybatis-config.xml 中定义 TypeHandler,以默认方式处理 Status。
<typeHandlers>
<typeHandler javaType="com.example.Status" handler="com.example.MyTypeHandler" />
</typeHandlers>
<typeHandlers>
<typeHandler javaType='Status' handler='StatusTypeHandler' />
</typeHandlers>
现在让我们考虑一个例子,假设您的Dao中有以下两个函数:
Status getStatusById(int code);
Status getStatusByName(String name);
你的映射器将会长成这个样子
<select id="getStatusById" resultType="Status" parameterType="int">
SELECT ls.id
FROM status AS ls
WHERE ls.id = #{id}
</select>
<select id="getStatusByName" resultType="Status" parameterType="String">
SELECT ls.id
FROM status AS ls
WHERE ls.name = #{name}
</select>
现在由于两个mapper的resultType都是Status,因此myBatis将使用CustomTypeHandler来处理这种类型,即StatusTypeHandler,而不是默认情况下用于处理枚举的EnumTypeHandler,因此您无需在数据库中维护正确的枚举名称。