0

映射器文件 employeeMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxxx.sample.test.dao.TestDAO">
<select id="selectEmployee" parameterType="int" resultMap="com.viasat.sample.domain.CreateDate" >
select createdate from employee where id = #{id}
</select>
</mapper>

映射器接口 TestDAO.java

public interface TestDAO {
public com.viasat.sample.domain.CreateDate selectEmployee(int id);
}

POJO Bean CreateDate.java

public class CreateDate {
private XMLGregorianCalendar createdate;
public XMLGregorianCalendar getCreatedate() {
return createdate;
}
public void setCreatedate(XMLGregorianCalendar createdate) {
this.createdate = createdate;
}
}

主要方法 MainClass.java

public class MainClass {
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
TestDAO tm = session.getMapper(TestDAO.class);
Map emp = tm.selectEmployee(123);
} catch (Exception e) {
e.printStackTrace();
}
finally {
session.close();
}
}
}

问题:从中检索的日期值(createdate)未映射/设置为 CreateDate bean 中的 XMLGregorianCalendar 类型 createdate。如果 createdate 的数据类型是 Date,它工作正常。简而言之,Mybatis 的 XMLGregorianCalendar 类型中没有设置 DATE 数据类型。

4

1 回答 1

0

创建自定义处理程序:

import java.sql.CallableStatement; 
import java.sql.Date; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar; 
import org.apache.ibatis.type.JdbcType; 
import org.apache.ibatis.type.TypeHandler; 
public class CustomDateTypeHandler implements TypeHandler { 
@Override 
public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) 
throws SQLException { 
if (null != parameter) { 
long time = ((XMLGregorianCalendar) parameter).toGregorianCalendar().getTimeInMillis(); 
Date date = new java.sql.Date(time); 
ps.setDate(i, date); 
} 
else { 
ps.setTimestamp(i, null); 
} 
} 
@Override 
public Object getResult(ResultSet rs, String columnName) throws SQLException { 
Date date = rs.getDate(columnName); 
if (null == date) { 
return null; 
} 
XMLGregorianCalendar date2 = null;
GregorianCalendar c = new GregorianCalendar();
c.setTime(date);
try {
date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
return date2;
} 
@Override 
public Object getResult(CallableStatement cs, int columnIndex) throws SQLException { 
return "";
} 
} 

在 Mybatis 配置 xml 文件中添加这个处理程序:

<typeHandler handler="com.viasat.cmdb.common.utils.CustomDateTypeHandler" javaType="javax.xml.datatype.XMLGregorianCalendar" />
</typeHandlers>
于 2013-07-15T05:14:50.037 回答