值'0000-00-00'不能表示为java.sql.Date

时间:2013-06-19 15:32:26

标签: java mysql hibernate spring-mvc java.util.date

我正在开发一些需要从数据库中提取数据的项目,我使用Spring MVC从DB构建模型来选择数据。

以下是 JSP页面的问题:

<form action="result" method="get" >
<table>
<thead>
<tr>
<th>Date to select:</th>
<th>Name to select:</th>
<th>Type to select:</th>
</tr>
</thead>

<tbody>
<tr>
<td><form:select  path="listOfDates">
<form:option value="NONE"> --SELECT--</form:option>
<form:options items="${listOfDates}"></form:options>
</form:select>
</td>  
<td><form:select  path="listOfInstitutionsNames">
<form:option value="NONE"> --SELECT--</form:option>
<form:options items="${listOfInstitutionsNames}"></form:options>
</form:select>
</td>
<td>
<form:select  path="listOfInstitutionsTypes">
<form:option value="NONE"> --SELECT--</form:option>
<form:options items="${listOfInstitutionsTypes}"></form:options>
</form:select>
</td>
</tr>
</tbody>

<tfoot>
<tr>
<td><input type="submit" value="Извлечь"/></td>
</tr>
</tfoot>

</table>
</form>

如您所见,我尝试使用<form:select>代码库中的Spring 问题:
但是当它使用控制器准备我的模型时

@Controller
public class HomeController{ 

    @Autowired
    private ControllerSupportClass controllerSupportClass; 


        @RequestMapping(value="/search", method=RequestMethod.GET)
        public String search(Model model) {
            List<Date> listOfDates = controllerSupportClass.findAllDatesForm();
            List<String> listOfInstitutionsNames = controllerSupportClass.findAllInstitutionsForm();
            List<String> listOfInstitutionsTypes = controllerSupportClass.findAllTypesForm();
            model.addAttribute("listOfInstitutionsTypes", listOfInstitutionsTypes);
            model.addAttribute("listOfInstitutionsNames", listOfInstitutionsNames);
            model.addAttribute("listOfDates", listOfDates);
            return "search";    
        }


        @RequestMapping(value ="/result", method=RequestMethod.GET)
        public String SecondActionPage(@RequestParam String particularDate, 
                                       @RequestParam String nameOfInstitution, 
                                       @RequestParam String typeName,
                                       Model model) throws Exception {


                if(particularDate !="" && nameOfInstitution.trim() !="" && typeName.trim()=="") {                   
                    controllerSupportClass.findWithDateAndName(nameOfInstitution, particularDate, model);                   
                } else if(particularDate.trim() !="" && nameOfInstitution.trim() =="" && typeName.trim() !="") {                    
                    controllerSupportClass.findWithAddedDateAndType(typeName, particularDate, model);                   
                } else if(particularDate.trim() !="" && nameOfInstitution.trim() =="" && typeName.trim() ==""){         
                    controllerSupportClass.findWithAddedDate(particularDate, model);    
                } else if(particularDate.trim() !="" && nameOfInstitution.trim() !="" && typeName.trim() !="") {
                    throw new Exception("Search by choose all parameters is not exceptable");   
                } else {    
                    throw new Exception("You didn't put any search parameters");    
                }           
            return "search";
        }

}

它给我一个错误:

  

警告:org.springframework.web.servlet.PageNotFound - 找不到映射   用于在DispatcherServlet中使用URI [/ controller /]的HTTP请求   name'appServlet'Hibernate:选择distinct creationda0_.DATE_ID as   DATE1_0_,creationda0_.CHILD_ADMISSION_DATE为CHILD2_0_,   creationda0_.CHILD_GO_SCHOOL_DATE为CHILD3_0_,   creationda0_.PARTICULAR_DATE为PARTICULAR4_0_,creationda0_.VERSION   来自CREATION_DATE creationda0_ WARN的VERSION0_:   org.hibernate.util.JDBCExceptionReporter - SQL错误:0,SQLState:   S1009错误:org.hibernate.util.JDBCExceptionReporter - 值   '0000-00-00'不能表示为java.sql.Date 2013年6月19日   3:26:53 PM org.apache.catalina.core.StandardWrapperValve调用   严重:servlet [appServlet]的Servlet.service()与上下文有关   path [/ controller]抛出异常[请求处理失败;嵌套   异常是org.hibernate.exception.GenericJDBCException:不能   执行查询]具有根本原因java.sql.SQLException:Value   '0000-00-00'不能表示为java.sql.Date

如果您需要我的Entity类,那么我在Date使用java.util,但我使用@Temporal注释将其从SQL转换为单元Date as我明白了:

@Entity
@Table(name="CREATION_DATE")
public class CreationDate implements Serializable {


    private int dateId;

        @Id
        @GeneratedValue(strategy=IDENTITY)
        @Column(name="DATE_ID")
        public int getDateId() {
            return dateId;
        }

        public void setDateId(int dateId) {
            this.dateId = dateId;
        }


    private int version;

        @Version
        @Column(name="VERSION")
        public int getVersion() {
            return version;
        }

        public void setVersion(int version) {
            this.version = version;
        }


    private Date particularDate;

        @Temporal(TemporalType.DATE)
        @DateTimeFormat(pattern="yyyy-MM-dd")
        @Column(name="PARTICULAR_DATE")
        public Date getParticularDate() {
            return particularDate;
        }

        public void setParticularDate(Date particularDate) {
            this.particularDate = particularDate;
        }


    private Date childGoSchoolDate;

        @Temporal(TemporalType.DATE)
        @DateTimeFormat(pattern="yyyy-MM-dd")
        @Column(name="CHILD_GO_SCHOOL_DATE")
        public Date getChildGoSchoolDate() {
            return childGoSchoolDate;
        }

        public void setChildGoSchoolDate(Date childGoSchoolDate) {
            this.childGoSchoolDate = childGoSchoolDate;
        }


    private Date childAdmissionDate;

        @Temporal(TemporalType.DATE)
        @DateTimeFormat(pattern="yyyy-MM-dd")
        @Column(name="CHILD_ADMISSION_DATE")
        public Date getChildAdmissionDate() {
            return childAdmissionDate;
        }

        public void setChildAdmissionDate(Date childAdmissionDate) {
            this.childAdmissionDate = childAdmissionDate;
        }


}

假设数据类型转换的问题是因为MVC使用String,但实际类型为Date

6 个答案:

答案 0 :(得分:32)

在MySql '0000-00-00'中被视为有效日期,但不能以java.sql.Date的形式重复。

您可以使用在日期为'0000-00-00'时返回NULL的查询,否则使用实际值:

SELECT
  CASE WHEN `date`!='0000-00-00' THEN `date` END new_date
FROM
  yourtable

或者您可以添加到您的数据源连接字符串:

zeroDateTimeBehavior=convertToNull

'0000-00-00'的日期将自动转换为NULL。

答案 1 :(得分:22)

使用JDBC-mysql协议附加以下语句:

"?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8"

例如:

jdbc:mysql://localhost/infra?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8

答案 2 :(得分:4)

zeroDateTimeBehavior=convertToNull添加到jdbc连接URL。

String jdbcUrl="jdbc:mysql://localhost:3306/master_schema?zeroDateTimeBehavior=convertToNull"

答案 3 :(得分:3)

问题并不总是NULL。您的数据集可能包含05/23/2005格式的日期,运行加载程序会导致它将0000-00-00插入您的DATE类型列。无效的DATEDATETIMETIMESTAMP值会转换为相应类型的“零”值('0000-00-00'或'0000-00-0000:00 :00')(来自MySQL手册)

在使用SELECT进行检索时,MySQL会以YYYY-MM-DD'格式检索'1000-01-01''9999-12-31'范围内的值。所以你所有的0000-00-00开始搞砸了。

因此,不仅要注意NULLs,还要注意MySQL不支持的日期格式。

支持RELAXED模式,其中任何字符都可以用作/05/23/2005之类的分隔符 - 您可能也想尝试这样做。

答案 4 :(得分:2)

我的猜测是你正在使用MySQL,你的日期列不是强制性的,因此可以包含NULL,但MySQL会做出愚蠢的事情并且会返回0000-00-00而不是NULL,除非你修复MySQL服务器设置。

答案 5 :(得分:2)

对我来说,仅仅以下工作。感谢 @Yogesh H Bhosale @fthiella 在同一个Q-A线程中回答我找到了提示,并对其进行了改进。

代码段:
连接字符串:

private static String CONNECTION_STR = "jdbc:mysql://localhost:3306/water_billing?zeroDateTimeBehavior=convertToNull";

SQL-DB实施:

为了防止在从返回的数据集中提取数据(日期字段)时出现Null Pointer Exception,我将以下代码添加到Prepared Statement中。

Connection conn = DriverManager.getConnection(CONNECTION_STR,USERNAME,PASSWORD);   //   Get connection to the DB to execute the query. You will have to handle exceptions here too..
String SQL = "SELECT dateField FROM my_payments_tbl";
ResultSet rs = conn.createStatement().executeQuery(SQL);
LocalDate prvPaymentDate = null;

while (rs.next())
{
     // Following is the next Important line.
     prvPaymentDate = (rs.getDate(1) != null) ? rs.getDate(1).toLocalDate() : null;    // Checks if it comes as a Null or a Real java.sql.Date object.

     // Depending on the value of the column in the current row, prvPaymentDate could be null.
     // Specially as we instructed via the Connection String, 0000-00-00 00:00:00 will come now as SQL NULL objects.
     // So we filter out them in the above line and assigns null, instead of LocalDate objects.
     if (prvPaymentDate != null)
        System.out.println("date "+prvPaymentDate.toString());
}

注意:
为了便于理解,请阅读答案中的所有评论。