在MyBatis中處理數據庫的枚舉類型通常有兩種方式:
public class EnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {
private Class<E> type;
public EnumTypeHandler(Class<E> type) {
this.type = type;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.name());
}
@Override
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
String value = rs.getString(columnName);
return Enum.valueOf(type, value);
}
@Override
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String value = rs.getString(columnIndex);
return Enum.valueOf(type, value);
}
@Override
public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String value = cs.getString(columnIndex);
return Enum.valueOf(type, value);
}
}
然后在MyBatis的配置文件中配置這個TypeHandler,例如:
<typeHandlers>
<typeHandler handler="com.example.EnumTypeHandler"/>
</typeHandlers>
public enum Status {
ACTIVE("A"),
INACTIVE("I");
private String value;
Status(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
public static Status fromString(String value) {
for (Status status : Status.values()) {
if (status.value.equals(value)) {
return status;
}
}
throw new IllegalArgumentException("Invalid value for Status: " + value);
}
}
在Mapper接口中使用枚舉類型:
public interface UserMapper {
void insertUser(@Param("name") String name, @Param("status") Status status);
User getUserByName(String name);
}
在配置文件中使用枚舉類型:
<insert id="insertUser" parameterType="map">
INSERT INTO user (name, status) VALUES (#{name}, #{status})
</insert>