datetime
The data in the format in MySQL is in the form of such as: 2021-01-14 13:52:00
Java's own java.sql.Date
, java.sql.Time
and java.sql.Timestamp
cannot be expressed in this form, so it is very inconvenient to involve this form of date during development.
If Java uses String to store this time format, you need to pay attention to the conversion between formats when reading and writing the database.
Read database
Use MySQL library functions DATE_FORMAT()
to datetime
process data of type in MySQL to obtain data of type String.
select DATE_FORMAT(`create_time`, "%y-%m-%d %H:%i:%s")as create_time from test_table;
resultMap
Specify as follows when defining in Mapper
<id column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
Write to the database
yyyy-MM-dd HH:mm:ss
Write the time in the String type format into the datetime
type field in MySQL , which can be written directly without conversion between formats.
You can also use lombok and Json related tools as follows
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class User {
private int id;
private String name;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:SS")
private Date bir;
private String sex;
private String address;
}
Used @JsonFormat
to specify the format of the returned Json each field.