springboot~mybatis里localdatetime序列化(hua)問題(ti)
問題起因
主(zhu)要是使用mybatis作為(wei)ORM之后(hou),返(fan)回的對象為(wei)Map,然(ran)后(hou)對于數據(ju)庫的datetime,datestamp類型返(fan)回為(wei)時間戳而(er)不是標準的時間,這個(ge)問題(ti)解決(jue)方案有兩種,大叔分(fen)析一下:
- 在mapper的select里,使用mysql這些數據庫的函數,dateformat進行轉化,
缺點,單元測試里使用h2數據庫時會找不到這些函數 - 在ObjectMapper反序列化時統一進行處理,這種方式更好,與具體數據庫解耦了
實現
引用依賴包
'org.mybatis:mybatis-typehandlers-jsr310:1.0.2',
'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.2'
添加組件類
/**
* 序列化localdatetime處理.
*/
@Component
public class JacksonConfig {
/**
* 注入時間處理.
*
* @return
*/
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JSR310Module());
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
return mapper;
}
}
成功解決問題
{
"pageCurrent": 1,
"pageSize": 10,
"pageTotal": 1,
"data": [
{
"freeDays": 8,
"city": "",
"leadingPerson": "",
"contactPerson": "zhangsan",
"source": 1,
"customerName": "i-counting",
"intention": 1,
"province": "",
"appointmentTime": "2018-09-20T00:00:00.000Z",
"createTime": "2018-09-27T06:33:49.000Z",
"telephoneStatus": 1,
"id": 10000,
"contactPhone": "135"
}
]
}