您的位置 首页 java

java利用枚举与数据库交互

我们可以配合 Mybatis 将数据库字段转换为枚举类型。现在假设有一个数据库字段 check_type 的类型如下:

 `check_type` int(1) DEFAULT NULL COMMENT '检查类型(1:未通过、2:通过)',  

复制代码它对应的枚举类型为 CheckType,代码如下:

 public enum CheckType {
	NO_PASS(0, "未通过"), PASS(1, "通过");
	 private  int key;
	private String text;
	private CheckType(int key, String text) {
		this.key = key;
		this.text = text;
	}
	public int getKey() {
		return key;
	}
	public String getText() {
		return text;
	}
	private  static  HashMap<Integer,CheckType> map = new HashMap<Integer,CheckType>();
	static {
		for(CheckType d : CheckType.values()){
			map.put(d.key, d);
		}
	}
	
	public static CheckType parse(Integer index) {
		if(map.containsKey(index)){
			return map.get(index);
		}
		return null;
	}
}  

1)CheckType 添加了 构造方法 ,还有两个字段,key 为 int 型,text 为 String 型。

2)CheckType 中有一个public static CheckType parse(Integer index)方法,可将一个 Integer 通过 key 的匹配转化为枚举类型。

那么现在,我们可以在 Mybatis 的配置文件中使用 typeHandler 将数据库字段转化为枚举类型。

 <resultMap id="CheckLog" type="com.entity.CheckLog">
  <id property="id" column="id"/>
  <result property="checkType" column="check_type" typeHandler="com.CheckTypeHandler"></result>
</resultMap>  

复制代码其中 checkType 字段对应的类如下:

 public class CheckLog implements Serializable {
    private String id;
    private CheckType checkType;
    public String getId() {
        return id;
    }
    public  void  setId(String id) {
        this.id = id;
    }
    public CheckType getCheckType() {
        return checkType;
    }
    public void setCheckType(CheckType checkType) {
        this.checkType = checkType;
    }
}  

复制代码CheckTypeHandler 转换器的类源码如下:

 public class CheckTypeHandler  extends  BaseTypeHandler<CheckType> {
	@ Override 
	public CheckType getNullableResult(ResultSet rs, String index) throws SQL Exception  {
		return CheckType.parse(rs.getInt(index));
	}
	@Override
	public CheckType getNullableResult(ResultSet rs, int index) throws SQLException {
		return CheckType.parse(rs.getInt(index));
	}
	@Override
	public CheckType getNullableResult(CallableStatement cs, int index) throws SQLException {
		return CheckType.parse(cs.getInt(index));
	}
	@Override
	public void setNonNullParameter(PreparedStatement ps, int index, CheckType val,  Jdbc Type arg3) throws SQLException {
		ps.setInt(index, val.getKey());
	}
}  

复制代码CheckTypeHandler 的核心功能就是调用 CheckType 枚举类的 parse() 方法对数据库字段进行转换。

文章来源:智云一二三科技

文章标题:java利用枚举与数据库交互

文章地址:https://www.zhihuclub.com/176186.shtml

关于作者: 智云科技

热门文章

网站地图