ibatis,鸟菜的理解就是:为java对象(通常是javabean)和数据库之间建立的一种映射关系。这种关系的存在,使得DBA不用去花时间了解JAVA代码,仅需要对sqlmap.xml文件进行审阅;同样使得java程序员不必过分关心于JDBC编写,只需要一种简单的映射关系,即可实现高效稳定的数据库操作。
差点跑题。对于DO(DataObject)中的枚举类型,如何实现同普通类型一样存取呢?刚接触Ibatis时觉得很困惑,其实最终的解决办法就是针对DO中枚举对象编写合适的setter/getter方法。talk is cheap,show code!
DO 中包含枚举类Type,其定义如下:
package com.taobao.mm.august;
public enum Type {
big(1,"big"),
small(0,"small"),
tiny(-1,"tiny");
private int code;
private String name;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private Type(int code,String name){
this.code = code;
this.name = name;
}
public static final Type getTypeByCode(int code){
Type tp = null;
for(Type e :Type.values()){
if(e.getCode()==code){
tp = e;
break;
}
}
return tp;
}
}
Do定义如下:
package com.taobao.mm.august;
public class TestDO {
//基本类型
private int id;
//枚举类型
private Type type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//这样写可以吗?不可以!
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
对于枚举类型的type来说,仅仅定义了setType(Type)和getType()方法是无法从满足ibatis中sqlmap映射的,因为:
在insert时,ibatis会调用TestDo中getter方法,将对应变量值取出,然后再生成Insert语句并执行。当取出的类型不是数值类型时,因无法识别所以将数据库中对应的相应字段置为空null;
在select时,ibatis将调用TestDo中setter方法,将数据库中值赋给DO中对象,从而拼装成完整的DO。
对于Type来说,getType()方法的返回值无法识别,因此插入数据库的是Null;
当select返回时,返回的是数值类型,无论是基本类还是包装类,都不满足setType(Type type)中Type类型,故DO中type字段值为Null;
为解决以上问题,只需要修改getType()和setType(Type type)方法:
package com.taobao.mm.august;
public class TestDO {
//基本类型
private int id;
//枚举类型
private Type type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//这样写可以吗?不可以!
// public Type getType() {
// return type;
// }
public void setType(Type type) {
this.type = type;
}
//返回基本类型
public int getType(){
return this.type.getCode();
}
//正确的参数 然后在内部转换 对于type.name也用同样方式处理
public void setType(int type){
this.type = Type.getTypeByCode(type);
}
}
问题解决。