MySQL建立Timestamp数据类型字段
Spring Data JPA相关类建立
建立对应实体类
import lombok.Data; import javax.persistence.*; import java.io.Serializable; import java.util.Date; /** * @author LiT * @date 2020/5/22 15:54 */ @Data @Entity @Table(name = "test") public class Test implements Serializable { /** * 测试-主键 */ @Id @Column(name = "id", length = 32) private String id; /** * 建立时间 yyyy-MM-dd HH:mm:ss */ @Column(name = "create_time", insertable = false, updatable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP") private Date createTime; /** * 修改时间 yyyy-MM-dd HH:mm:ss */ @Column(name = "update_time", insertable = false, updatable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP") private Date updateTime; }
建立对应Repository
import com.lit.domain.Test; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * @author LiT * @date 2020/5/22 16:11 */ @Repository public interface TestRepository extends JpaRepository<Test, String> { }
建立简单Service(省略接口开发)
import com.lit.domain.Test; import com.lit.repository.TestRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.UUID; /** * @author LiT * @date 2020/5/22 16:14 */ @Service public class TestService { @Autowired private TestRepository testRepository; /** * 简单查询全部 * * @return */ private List findAll() { List<Test> testList = null; try { testList = testRepository.findAll(); } catch (Exception e) { e.printStackTrace(); return null; } return testList; } /** * 简单插入 * * @return */ private Boolean save(Test test) { try { testRepository.save(test); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
建立测试Resource
import com.lit.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author LiT * @date 2020/5/22 16:19 */ @RestController @RequestMapping("/asp/test") public class TestResource { @Autowired private TestService testService; /** * 简单查询全部 * * @return */ @GetMapping("/find-all") private List findAll() { return testService.findAll() } /** * 简单插入 * * @return */ @PostMapping("/save") private Boolean save(@RequestBody Test test) { return testService.save(test); } }
开始测试
测试插入
测试查询
查询数据库数据
疑问
//观察到数据库时间为2020-06-01 17:29:44 ("yyyy-MM-dd HH:mm:ss"), //可是java查询出为2020-06-01 17:29:44.0("yyyy-MM-dd HH:mm:ss E"), //简单解决格式化时间 SimpleDateFormat format=new SimpleDateFormat("MM-dd HH:mm:ss E"); String time=format.format(new Date()); System.out.println("当前时间: "+time);