溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在MyBatis中自動插入時間戳

發(fā)布時間:2024-09-06 16:35:41 來源:億速云 閱讀:81 作者:小樊 欄目:編程語言

在 MyBatis 中,可以通過編寫自定義類型處理器(TypeHandler)來實現(xiàn)自動插入時間戳。以下是一個簡單的示例:

  1. 首先,創(chuàng)建一個自定義類型處理器,用于將當(dāng)前時間戳轉(zhuǎn)換為數(shù)據(jù)庫所需的格式。例如,如果你使用的是 MySQL,可以創(chuàng)建一個名為 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;

    // ...
}

現(xiàn)在,當(dāng)你插入數(shù)據(jù)時,MyBatis 會自動將當(dāng)前時間戳插入到 createdAt 字段中。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI