温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在MyBatis中自动插入时间戳

发布时间:2024-09-06 16:35:41 来源:亿速云 阅读:79 作者:小樊 栏目:编程语言

在 MyBatis 中,可以通过编写自定义类型处理器(TypeHandler)来实现自动插入时间戳。以下是一个简单的示例:

  1. 首先,创建一个自定义类型处理器,用于将当前时间戳转换为数据库所需的格式。例如,如果你使用的是 MySQL,可以创建一个名为 TimestampTypeHandler 的类:
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

@MappedTypes(Date.class)
public class TimestampTypeHandler extends BaseTypeHandler<Date> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, new Timestamp(parameter.getTime()));
    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnName);
        return timestamp == null ? null : new Date(timestamp.getTime());
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(columnIndex);
        return timestamp == null ? null : new Date(timestamp.getTime());
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp timestamp = cs.getTimestamp(columnIndex);
        return timestamp == null ? null : new Date(timestamp.getTime());
    }
}
  1. 在 MyBatis 配置文件(例如 mybatis-config.xml)中注册自定义类型处理器:
    <!-- ... -->
    <typeHandlers>
        <typeHandler handler="com.example.TimestampTypeHandler" />
    </typeHandlers>
</configuration>
  1. 在实体类中,为需要自动插入时间戳的字段添加 @ColumnType 注解,指定使用自定义类型处理器:
import org.apache.ibatis.type.ColumnType;

public class YourEntity {
    // ...

    @ColumnType(typeHandler = TimestampTypeHandler.class)
    private Date createdAt;

    // ...
}

现在,当你插入数据时,MyBatis 会自动将当前时间戳插入到 createdAt 字段中。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI