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

[英]Value '0000-00-00' can not be represented as java.sql.Date


I'm working on some project which needs to extract data from DB and I use Spring MVC to build model from DB for selecting data.

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

Here is the problem with my JSP page:

这是我的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>

As you can see I try to use <form:select> from Spring tag library.
Question:
but when it's preparing my model with this controller:

如您所见,我尝试使用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";
        }

}

It gives me an error like this:

它给我一个这样的错误:

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/controller/] in DispatcherServlet with name 'appServlet' Hibernate: select distinct creationda0_.DATE_ID as DATE1_0_, creationda0_.CHILD_ADMISSION_DATE as CHILD2_0_, creationda0_.CHILD_GO_SCHOOL_DATE as CHILD3_0_, creationda0_.PARTICULAR_DATE as PARTICULAR4_0_, creationda0_.VERSION as VERSION0_ from CREATION_DATE creationda0_ WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: S1009 ERROR: org.hibernate.util.JDBCExceptionReporter - Value '0000-00-00' can not be represented as java.sql.Date Jun 19, 2013 3:26:53 PM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [appServlet] in context with path [/controller] threw exception [Request processing failed; nested exception is org.hibernate.exception.GenericJDBCException: could not execute query] with root cause java.sql.SQLException: Value '0000-00-00' can not be represented as java.sql.Date

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

If you need my Entity class it's here I'm using Date from java.util, but I go with @Temporal annotation to convert it from SQL to unit Date as I understand:

如果您需要我的Entity类,那么我在这里使用来自java.util的Date,但是我使用@Temporal注释将它从SQL转换为单位Date,据我了解:

@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;
        }


}

Assuming that the problem with data type conversion is because MVC uses String, but the actual type is Date.

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

5 个解决方案

#1


28  

In MySql '0000-00-00' is considered a valid date, but it can't be repesented as java.sql.Date.

在MySql中,'0000-00-00'被认为是一个有效的日期,但它不能被重复为java.sql.Date。

You could use a query that returns NULL in case date is '0000-00-00', or the actual value otherwise:

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

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

or you can add to your datasource connection string this:

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

zeroDateTimeBehavior=convertToNull

and dates as '0000-00-00' will be automatically converted to NULL.

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

#2


20  

Append the following statement with the JDBC-mysql protocol:

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

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

for Example:

例如:

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

#3


3  

It is NOT always the NULL issue. Your data set may contain dates in the format 05/23/2005 and running the loader will cause it to insert 0000-00-00 into your DATE type column. Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00' or '0000-00-00 00:00:00') (from MySQL manual)

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

While retrieving using a SELECT, MySQL retrieves the value in YYYY-MM-DD' format in the range of '1000-01-01' to '9999-12-31'. So all your 0000-00-00 starts screwing up.

在使用SELECT进行检索时,MySQL以“1000-01-01”到“9999-12-31”的范围检索YYYY-MM-DD'格式的值。所以你所有的麻烦都开始搞砸了。

So watch out not just for NULLs but also for date formats not supported by MySQL.

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

There is RELAXED mode supported where any character can be used as delimiters like / in 05/23/2005 - you may want to try that as well.

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

#4


2  

My wild guess is that you're using MySQL, your date columns are not mandatory and hence can contain NULLs, but MySQL does idiotic things and will return 0000-00-00 instead of NULL unless you fix the MySQL server settings.

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

#5


2  

For me simply the following worked. Thanks to @Yogesh H Bhosale and @fthiella answer in this same Q-A thread I found the hint, and improved it.

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

Code Snippet:
Connection String:

代码片段:连接字符串:

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

SQL-DB implementation:

SQL-DB实现:

And to prevent from Null Pointer Exception at the time of data(date field) extraction from the returned data set I add the following code to the Prepared Statement.

并且为了防止从返回的数据集中提取数据(日期字段)时出现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());
}

Note:
Please read all the comments within the answer for good understanding.

注意:请阅读答案中的所有评论,以便更好地理解。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/06/19/54cfe8d30133723626aa23b928c6ebff.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告