timestamp或datetime的匹配
存放毫秒
在資料庫中預設的精度為秒,如果需要存放毫秒甚至更好,可以如下:
CREATE TABLE Ticket ( TicketId BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, UserId BIGINT UNSIGNED NOT NULL, Subject VARCHAR(255) NOT NULL, Body TEXT,-- 精度為0.000001秒 DateCreated TIMESTAMP(6) NULL, CONSTRAINT Ticket_UserId FOREIGN KEY (UserId) REFERENCES UserPrincipal (UserId) ON DELETE CASCADE) ENGINE = InnoDB;-- 精度為毫秒`DateCreated` datetime(3) NULL DEFAULT NULL,
匹配為java.sql.Timestamp這是可以直接匹配
private Timestamp dateCreated;@Basicpublic Timestamp getDateCreated() {return dateCreated;}public void setDateCreated(Timestamp dateCreated) {this.dateCreated = dateCreated;}
但java.sql.Timestamp不是很好使用,一般我們可以將其轉換為Instant
Instant instant = Instant.now();entity.setDateCreated(new Timestamp(now().toEpochMilli()));
和LocalDateTime的轉換
目前並不支援和LocalDateTime的直接轉換,但是我們可以通過一些小技巧,讓用起來,就如同直接轉換那樣。
@Entitypublic class TestEntity implements Serializable{ private LocalDateTime createTime; // 採用private,也就是資料庫的列的匹配並不直接開發出來,對使用者隱藏。 @Basic @Column(name="create_time") private String getCreateTimeStr() { return createTime== null ? null : createTime.toString(); } // setter同樣採用private,這裡的轉換某種意義上是不規範的,沒有考慮ISO8601中時區Z等攜帶資訊,正式代碼中需要補齊,這裡只是簡單測試 @Basic @Column(name="create_time") private void setCreateTimeStr(String createTimeStr) { try{ if(StringUtils.isBlank(createTimeStr)) this.createTime = null; else this.createTime = LocalDateTime.parse(createTimeStr.replace(' ', 'T')); }catch(Exception e){ this.createTime = null; } } @Transient public LocalDateTime getCreateTime() { return createTime; } @Transient public void setCreateTime(LocalDateTime createTime) { this.createTime= createTime; } ......}
採用Convert進行轉換
前面的LocalDateTime的轉換其實正規的應該使用Converter,下面以json儲存的轉換為對象為例子。假設是資料庫的某一列使用text,存放的是json資料。我們可以用類似上面講述的方式直接擷取對象。
@Entitypublic class TestPage implements Serializable{private long id;private String userName;private String emailAddress;private Address address; //將資料庫中以json text存放的資訊和對象直接管理... ...@Convert(converter=AddressConverter.class)public Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}public static class AddressConverter implements AttributeConverter<Address, String> {private static final Gson gson = new Gson();@Overridepublic String convertToDatabaseColumn(Address attribute) {return gson.toJson(attribute);}@Overridepublic Address convertToEntityAttribute(String dbData) {return gson.fromJson(dbData, Address.class);} }}
關於gsongson是json解析器,非常好使用。下面是其在pom.xml引入
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.7</version></dependency>
我們希望直接將"time":"2018-01-12T09:47:51.411"直接映射為LocalDateTime。同樣這裡的轉碼只是為了測試便利,沒有考慮ISO8601中時區Z等攜帶資訊,正式代碼中需要補齊。
public static Gson createGson(){return new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() { @Override public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString()); } }).registerTypeAdapter(LocalDateTime.class,new JsonSerializer<LocalDateTime>() {@Overridepublic JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {return new JsonPrimitive(src.toString());}}).create();}相關連結: 我的Professional Java for Web Applications相關文章