mysql日期儲存為int,mybatis做ORM對映與java.util.Date的轉換問題
阿新 • • 發佈:2019-01-01
在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>