映射文件 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的数据类型是Date,它可以正常工作。简而言之,DATE数据类型未在Mybatis中的XMLGregorianCalendar类型中设置。
答案 0 :(得分: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 Configuration xml文件中添加此处理程序:
<typeHandler handler="com.viasat.cmdb.common.utils.CustomDateTypeHandler" javaType="javax.xml.datatype.XMLGregorianCalendar" />
</typeHandlers>