問題起因
主要是使用mybatis作為ORM之后,返回的對象為Map,然后對於數據庫的datetime,datestamp類型返回為時間戳而不是標准的時間,這個問題解決方案有兩種,大叔分析一下:
- 在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"
}
]
}