基礎Class和TypeHandler
MyBatis操作的基本User對象結構如下:
@Data
@Alias(value = "user")
public class User implements Serializable {
private static final long serialVersionUID = -4947062488310146862L;
private Long id;
@NotNull(message = "用戶名不能爲空")
private String userName;
@NotNull(message = "備註不能爲空")
private String note;
@NotNull(message = "性別不能爲空")
private SexEnum sex;
}
其中sex字段對應的類型爲SexEnum枚舉類型,因此同時設置瞭如下的TypeHandler,從而在前端傳入參數和從數據庫中取值時進行自動的名稱轉換。
@MappedJdbcTypes(JdbcType.INTEGER)
@MappedTypes(value = SexEnum.class)
public class SexTypeHandler extends BaseTypeHandler<SexEnum> {
/**
* 設置非空性別參數
*/
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, SexEnum sexEnum, JdbcType jdbcType) throws SQLException {
preparedStatement.setInt(i, sexEnum.getId());
}
/**
* 通過列名讀取性別
*/
@Override
public SexEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
int sex = resultSet.getInt(s);
if (sex != 1 && sex != 2) {
return null;
}
return SexEnum.getEnumById(sex);
}
/**
* 通過下標讀取性別
*/
@Override
public SexEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
int sex = resultSet.getInt(i);
if (sex != 1 && sex != 2) {
return null;
}
return SexEnum.getEnumById(sex);
}
/**
* 通過存儲過程讀取性別
*/
@Override
public SexEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
int sex = callableStatement.getInt(i);
if (sex != 1 && sex != 2) {
return null;
}
return SexEnum.getEnumById(sex);
}
}
請求參數解析問題
下面在使用axios post請求來更新用戶信息,請求的JSON參數如下:
{
id: id,
userName: username,
sex: sex === 'MALE' ? 1 : 2, // 1: 男,2: 女
note: note
}
其中由於sex字段的枚舉類型,因此這裏將sex根據select得到的option來轉換爲了枚舉中的id對應的值。也就是:
1: MALE
2: FAMALE
但在發出請求之後,服務端日誌中出現如下的問題:
2020-03-02 22:59:50.722 WARN 10864 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `cn.zyt.springbootlearning.domain.SexEnum` from number 2: index value outside legal index range [0..1]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `cn.zyt.springbootlearning.domain.SexEnum` from number 2: index value outside legal index range [0..1]
at [Source: (PushbackInputStream); line: 1, column: 40] (through reference chain: cn.zyt.springbootlearning.domain.User["sex"])]
問題解決
對於該問題,可以使用枚舉類型的desc來作爲參數傳遞。當使用如下desc屬性映射時,將JSON請求參數改成如下就可以解析成功不報錯:
{
id: id,
userName: username,
sex: sex,
note: note
}
此時對應的sex字段選擇select標籤如下:
<tr>
<td>sex:</td>
<td><select name="sex" value={sex} onChange={this.handleChange}>
<option value="MALE">MALE</option>
<option value="FEMALE">FEMALE</option>
</select></td>
</tr>
同時注意:enum字段sex對應的數據庫列的設置中,該列的數據類型爲int,而不能爲tinyint。tinyint數據類型對應於java中的boolean,1表示true,0表示false。