您好,登錄后才能下訂單哦!
在 MyBatis 中,可以通過編寫自定義類型處理器(TypeHandler)來實現(xiàn)自動插入時間戳。以下是一個簡單的示例:
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());
}
}
mybatis-config.xml
)中注冊自定義類型處理器: <!-- ... -->
<typeHandlers>
<typeHandler handler="com.example.TimestampTypeHandler" />
</typeHandlers>
</configuration>
@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
字段中。
免責(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)容。