14

DBからデータを抽出する必要があるプロジェクトに取り組んでおり、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";
        }

}

次のようなエラーが表示されます。

パス [/controller] のコンテキストでサーブレット [appServlet] の service() が例外をスローしました [要求処理に失敗しました。ネストされた例外は org.hibernate.exception.GenericJDBCException: クエリを実行できませんでした] 根本原因 java.sql.SQLException: 値 '0000-00-00' は java.sql.Date として表現できません

私のEntityクラスが必要な場合は、Datefromを使用してjava.utilいますが、@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;
        }


}

データ型変換の問題は MVC が を使用しているためだと仮定しますStringが、実際の型はDateです。

4

6 に答える 6

23

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
于 2014-06-07T04:52:50.687 に答える
3

私にとっては、単に次のように機能しました。この同じQAスレッドの@Yogesh H Bhosale@fthiellaの回答のおかげで、ヒントを見つけて改善しました。

コード スニペット:
接続文字列:

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

注:
理解を深めるために、回答内のすべてのコメントをお読みください。

于 2015-10-08T07:00:33.927 に答える
3

それは常にNULL問題ではありません。データセットにはフォーマットの日付が含まれている場合があり05/23/2005、ローダーを実行すると0000-00-00、DATE タイプの列に挿入されます。DATE、、DATETIMEまたは無効なTIMESTAMP値は、適切なタイプ ('0000-00-00' または '0000-00-00 00:00:00') の「ゼロ」値に変換されます (MySQL マニュアルより)

を使用してSELECT取得する場合、MySQL は から の範囲の形式で値を取得しYYYY-MM-DD'ます。だからあなたのすべての始まりは台無しです。'1000-01-01''9999-12-31'0000-00-00

NULLsそのため、MySQL でサポートされていない日付形式だけでなく、日付形式にも注意してください。

/のように任意の文字を区切り文字として使用できる RELAXED モードがサポートされ05/23/2005ています。それも試してみてください。

于 2013-11-05T21:54:36.270 に答える
2

私の推測では、あなたは MySQL を使用しており、日付列は必須ではないため、NULL を含めることができますが、MySQL サーバーの設定を修正しない限り、MySQL はばかげたことを行い、NULL ではなく 0000-00-00 を返します。

于 2013-06-19T15:43:17.187 に答える