Conversion between datetime data type in MySQL and String type in java

datetimeThe data in the format in MySQL is in the form of such as: 2021-01-14 13:52:00Java's own java.sql.Date, java.sql.Timeand java.sql.Timestampcannot 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 datetimeprocess 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;

resultMapSpecify as follows when defining in Mapper

<id column="create_time" property="createTime" jdbcType="TIMESTAMP"/>

Write to the database

yyyy-MM-dd HH:mm:ssWrite the time in the String type format into the datetimetype 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 @JsonFormatto specify the format of the returned Json each field.

Guess you like

Origin blog.csdn.net/qq_27198345/article/details/112605258