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);