Cannot convert '0000-00-00 00:00:00' to TIMESTAMP

后端 未结 2 1710
囚心锁ツ
囚心锁ツ 2020-12-30 21:11

the field definition

 /** Date. */
  @Column(columnDefinition = \"datetime\")
  private Date date;

setter

public void setDa         


        
相关标签:
2条回答
  • 2020-12-30 21:39

    I'm going to take a wild guess here that you're using MySQL :-) It uses "zero dates" as special placeholder - unfortunatelly, JDBC can not handle them by default.

    The solution is to specify "zeroDateTimeBehavior=convertToNull" as parameter to your MySQL connection (either in datasource URL or as an additional property), e.g.:

    jdbc:mysql://localhost/myDatabase?zeroDateTimeBehavior=convertToNull
    

    This will cause all such values to be retrieved as NULLs.

    0 讨论(0)
  • 2020-12-30 21:41

    I don't understand the point in your code, where you format then parse again a date. This seems like an identical operation. Maybe you could elaborate?


    If you want to give a default value to a date, you could do :

    /** Jan 1, 1970 ; first moment in time in Java */
    private static final Date NO_DATE = new Date(0L);
    
    private Date date;
    
    public void setDate(final Date date) {
         if (date == null) {
             this.date = NO_DATE;
         } else {
             this.date = date;
         }
    }
    

    Note : the annotation are optionnal, here I didn't add them.

    In this code, you could substitute what you want to the condition, and to the default value.

    You could also add a similar setter, that would take a String argument, and check for your special "00000..." value. This would allow for setting the field either with a Date, or with a String.

    0 讨论(0)
提交回复
热议问题