温馨提示×

mybatis日期转字符串如何实现

小亿
312
2024-05-28 18:22:14
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在MyBatis中,可以使用TypeHandler来实现日期类型转换为字符串类型的功能。以下是一个简单的DateToStringTypeHandler示例:

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateToStringTypeHandler implements TypeHandler<String> {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter);
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        Date date = rs.getDate(columnName);
        return dateFormat.format(date);
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        Date date = rs.getDate(columnIndex);
        return dateFormat.format(date);
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        Date date = cs.getDate(columnIndex);
        return dateFormat.format(date);
    }
}

然后在MyBatis配置文件中注册这个TypeHandler:

<typeHandlers>
    <typeHandler handler="com.example.DateToStringTypeHandler"/>
</typeHandlers>

在需要进行日期转换的地方,直接使用String类型即可,MyBatis会自动调用对应的TypeHandler来进行转换。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:java日期转字符串怎么实现

0