JPA和MySQL转换:
@Column(name = "registration_date")
private LocalDateTime registrationDate;
为TINYBLOB列类型。
现在,MySQL数据库中TINYBLOB中的日期已满。
在新的Spring Boot v2.2.5中解决此问题的正确方法是什么?
是否应该将所有TINYBLOB列直接以某种方式直接转换为MySQL数据库中的任何其他日期类型? 从数据库中获取日期时,是否应使用AttributeConverter接口进行转换?
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Object> {
@Override
public Object convertToDatabaseColumn(LocalDateTime locDateTime) {
return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Object tinyBlob) {
if (sqlTimestamp != null) {
// somehow convert tinyblob to LocalDateTime?
}
return null;
}
}
答案 0 :(得分:0)
这是解决方案。这个人帮了我:https://stackoverflow.com/a/8504540/1177067
<div class="a">
</div>
请注意:
import java.time.LocalDateTime;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Object> {
@Override
public Object convertToDatabaseColumn(LocalDateTime locDateTime) {
return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Object sqlTimestamp) {
if (sqlTimestamp != null) {
try {
byte[] dbBytes = (byte[]) sqlTimestamp;
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(dbBytes));
LocalDateTime covertedDateFromBytes = (LocalDateTime) ois.readObject();
ois.close();
return covertedDateFromBytes;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
}
return null;
}
正在以一种新的方式(例如时间戳记)存储日期,因此请确定您是想进一步使用tinyblob还是将新方法与时间戳记一起使用。