乐者为王

Do one thing, and do it well.

在iBatis中如何将JavaBean的boolean值映射成数据库的CHAR(Y或N)值

Spring 1.2.8 + iBatis 2.1.5

JavaBean的boolean值映射到数据库的默认值是0和1,不是非常直观,现在希望能将boolean值映射成为Y和N。iBatis 2.0.5以后的版本提供了TypeHandlerCallback,可以用来解决这个问题。

首先定义数据表:

1
2
3
4
5
6
CREATE TABLE users (
    username varchar(40),
    password varchar(255),
    enabled char(1),
    PRIMARY KEY (username)
) ENGINE=InnoDB DEFAULT CHARSET=utf-8;

YesNoTypeHandlerCallback实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class YesNoTypeHandlerCallback implements TypeHandlerCallback {

    public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
        if (parameter == null) {
            setter.setString("");
        } else {
            Boolean b = (Boolean)parameter;
            if (b.booleanValue()) {
                setter.setString("Y");
            } else {
                setter.setString("N");
            }
        }
    }

    public Object getResult(ResultGetter getter) throws SQLException {
        String string = getter.getString();
        if (string == null) {
            return null;
        } else if ("Y".equalsIgnoreCase(string)) {
            return new Boolean(true);
        } else {
            return new Boolean(false);
        }
    }

    public Object valueOf(String s) {
        return s;
    }
}

配置文件sql-map-config.xml中的内容如下:

1
2
3
4
5
6
<sqlMapConfig>
    <typeHandler jdbcType="CHAR" javaType="boolean"
                 callback="com.codemany.netlink.dao.support.YesNoTypeHandlerCallback" />

    <sqlMap resource="com/codemany/netlink/dao/impl/User.xml" />
</sqlMapConfig>

jdbcType="CHAR" javaType="boolean"必须有,否则YesNoTypeHandlerCallback.setParameter()不会被调用。

SqlMap映射文件User.xml部分代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<typeAlias alias="user" type="com.codemany.netlink.model.User" />

<resultMap id="userResult" class="user">
    <result property="username" column="username" />
    <result property="password" column="password" />
    <result property="enabled" column="enabled" jdbcType="CHAR" javaType="boolean" />
</resultMap>

<select id="getUser" parameterClass="string" resultMap="userResult">
<![CDATA[
    SELECT username, password, enabled
    FROM user WHERE username = #username#
]]>
</select>

<insert id="addUser" parameterClass="user">
<![CDATA[
    INSERT INTO user (username, password, enabled)
    VALUES (#username#, #password#, #enabled,jdbcType=CHAR,javaType=boolean#)
]]>
</insert>

jdbcType="CHAR" javaType="boolean"必须有,否则YesNoTypeHandlerCallback.getResult()不会被调用;#enabled,jdbcType=CHAR,javaType=boolean#也必须这样写,否则YesNoTypeHandlerCallback.setParameter()也不会被调用,写成#enabled:CHAR#或#enabled#都不起作用。

Comments