java - 如何在 MyBatis 中将整数转换为枚举?
问题描述
我有以下内容:
public class Stat {
public enum HitType {
MOBILE1(0), MOBILE2(1), DESKTOP(2);
public final int value;
public int value() { return value; }
HitType(int val) {
value = val;
}
public static HitType parseInt(int i) {
switch (i) {
case 0: return MOBILE1;
case 1: return MOBILE2;
case 2: return DESKTOP;
default: return null;
}
}
}
public HitType hitType;
public long sourceId;
public Stat(... int hitType, BigInteger sourceId) {
this.hitType = HitType.parseInt(hitType);
this.sourceId = sourceId.longValueExact();
@Mapper
public interface StatMapper {
@Select("select * from stats where id = #{id}")
@Results(value = {
@Result(property = "hitType", column = "hit_type"),
...
})
public Stat findById(@Param("id") long id);
Stat s = statMapper.findById(1);
response.getOutputStream().print(s.toString());
它仍然给出这个错误:
处理程序执行导致的已解决异常:org.mybatis.spring.MyBatisSystemException:嵌套异常是 org.apache.ibatis.executor.result.ResultMapException:尝试从结果集中获取列“hit_type”时出错。原因:java.lang.IllegalArgumentException:没有枚举常量 com.company.app.model.Stat.HitType.2
我尝试了http://stackoverflow.com/questions/5878952/ddg#5878986并阅读Convert integer value to matching Java Enum。
如果我将构造函数签名更改为
public Stat(..., int hitType, long sourceId) {
this.sourceId = sourceId;
然后它给出了错误
嵌套异常是 org.apache.ibatis.executor.ExecutorException: No constructor found in com.company.app.model.Stat 匹配 [java.math.BigInteger, java.lang.String, java.sql.Timestamp, java.lang.整数,java.math.BigInteger]
因此,在第一种情况下,它可能直接设置属性,而在第二种情况下,它正在使用构造函数。
我尝试HitType hitType
输入构造函数签名,但它仍然给我No constructor found...
错误。
MyBatis 3.4.5、MyBatis-Spring 1.3.1、Spring-Boot 1.5.13
解决方案
我为该类型添加了 getter & setter
public HitType getHitType() {
return hitType;
}
public void setHitType(int hitType) {
this.hitType = HitType.parseInt(hitType);
}
然后它开始工作。这很奇怪,因为它抱怨构造函数签名。如果它使用构造函数,为什么需要 getter 和 setter?
推荐阅读
- html - CSS过渡如何用于增加悬停时的Bootstrap卡片字体大小?
- java - 如何在特定端口上搜索响应式套接字服务器(如何连接到给定端口但没有其 ip 的服务器)?
- android - 是否有任何方法可以更改 viewPager 的滑动方向。我想在向上滑动时更改片段
- javascript - discord.js删除消息功能的问题
- google-apps-script - 如何从 HTML 服务中的列表框中获取值
- ios - 按下返回键时如何通过多个文本字段输入进行选项卡?
- oracle - 如何在 oracle sql 12.2.0.1.0 中授予引用?
- android - RecycleView 2 columns with horizontally expandable card
- r - 使用由 R 中的多个多边形组成的 shapefile 从 NetCDF 中提取数据?
- scala - Scala / Java,总结数据集中的两个数组列