在mysql做数据库的应用中,日期类型经常回存储为int(10)类型。方便排序和计算。但是在java中用Date.getTime返回的是13位的Long。并且在实体中我们如果用long来存储会有诸多不便。所以涉及到了转换问题。在我的项目中,用的是mybatis做持久性框架。对于这个问题用了以下方法处理。
- 用mybatis generate时,配置实体中用date来覆盖数据库中的int类型。
<columnOverride column="birthday" javaType="java.util.Date" jdbcType="INTEGER" />
- 自定义TypeHandler实现TypeHandler接口
@MappedTypes({ Date.class })
@MappedJdbcTypes({ JdbcType.INTEGER })
public class DateIntTypeHandler implements TypeHandler<Date> {
@Override
public void setParameter(PreparedStatement ps, int i, Date parameter,
JdbcType jdbcType) throws SQLException {
if (parameter == null) {
if (jdbcType == null) {
throw new TypeException(
"JDBC requires that the JdbcType must be specified for all nullable parameters.");
}
try {
ps.setNull(i, jdbcType.TYPE_CODE);
} catch (SQLException e) {
throw new TypeException(
"Error setting null for parameter #"
+ i
+ " with JdbcType "
+ jdbcType
+ " . "
+ "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. "
+ "Cause: " + e, e);
}
} else {
int time = (int) (parameter.getTime() / 1000);
ps.setInt(i, time);
}
}
@Override
public Date getResult(ResultSet rs, String columnName) throws SQLException {
int res = rs.getInt(columnName);
long time = res * 1000L;
return new Date(time);
}
@Override
public Date getResult(ResultSet rs, int columnIndex) throws SQLException {
int res = rs.getInt(columnIndex);
long time = res * 1000L;
return new Date(time);
}
@Override
public Date getResult(CallableStatement cs, int columnIndex)
throws SQLException {
int res = cs.getInt(columnIndex);
long time = res * 1000L;
return new Date(time);
}
}
- 在mybatis的配置中引用自定义的转换处理类
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:sqlmap/mysql/module/*/*.xml"></property>
<strong><property name="typeHandlers">
<array>
<bean name="dateIntTypeHandler" class="*.utils.mybatis.DateIntTypeHandler" />
</array>
</property></strong>
</bean>