2015-11-21 21 views
2

使用java.sql。Java SQL空對象引發MySQLIntegrityConstraintViolationException並且未定製異常

使用下面的類與數據庫對象執行操作:

public class TaskBusinessLogic 
{ 
    private TaskDao taskDao = null; 

    public TaskBusinessLogic(){ 
     taskDao = new TaskDaoImpl(); 
    } 

    /** 
    * Updates data in the table 'tasks' in the database 
    * @param task Record in the table 'tasks' in the database to be updated 
    * @throws ValidationException 
    */ 
    public void updateTask(Task task) throws ValidationException 
    { 
     cleanTask(task); 
     validateTask(task); 
     taskDao.updateTask(task); 
    } 

    private void cleanTask(Task task) 
    { 
     if(task.getTitle() != null) 
     { 
      task.setTitle(task.getTitle().trim()); 
     } 
     if(task.getPriority() != null) 
     { 
      task.setPriority(task.getPriority().trim()); 
     } 
     if(task.getNote() != null) 
     { 
      task.setNote(task.getNote().trim()); 
     } 
    } 

    private void validateTask(Task task) throws ValidationException 
    { 
     validateString(task.getTitle(), "Title", TITLE_MAX_LENGTH, true); 
     validateString(task.getPriority(), "Priority", PRIORITY_MAX_LENGTH, true); 
     validateString(task.getNote(), "Note", NOTE_MAX_LENGTH, true); 
     validateDate(task.getDateCompleted()); 
     validatePriority(task.getPriority()); 
    } 

    private void validateString(String value, String fieldName, int maxLength, boolean isNullAllowed) 
      throws ValidationException 
    { 
     if(value == null && isNullAllowed) 
     { 
      // return; // null permitted, nothing to validate 
     } 
     else if(!isNullAllowed && value == null) 
     { 
      throw new ValidationException(String.format("%s cannot be null", fieldName)); 
     } 
     else if(value.length() == 0) 
     { 
      throw new ValidationException(String.format("%s cannot be empty", fieldName)); 
     } 
     else if(value.length() > maxLength) 
     { 
      throw new ValidationException(String.format("%s cannot exceed %d characters", 
        fieldName, maxLength)); 
     } 
    } 
} 

和下面的類來擴展例外:

public class ValidationException extends Exception 
{ 
    public ValidationException() 
    { 
     super("Data not in valid format"); 
    } 

    public ValidationException(String message) 
    { 
     super(message); 
    } 


    public ValidationException(String message, Throwable throwable) 
    { 
     super(message, throwable); 
    } 

    public ValidationException(Throwable throwable) 
    { 
     super(throwable); 
    } 
} 

編輯:這此updateTask方法:

public void updateTask(Task task) 
    { 
     Connection connection = null; 
     PreparedStatement pStatement = null; 
     try{ 
      DataSource ds = new DataSource(); 
      connection = ds.createConnection(); 
      pStatement = connection.prepareStatement("UPDATE tasks SET Title = ?, Priority = ?, IsComplete = ?, "DateCompleted = ?, Note = ? WHERE TaskID = ?"); 
      pStatement.setString(1, task.getTitle()); 
      pStatement.setString(2, task.getPriority()); 
      pStatement.setBoolean(3, task.getIsComplete()); 
      pStatement.setDate(4, task.getDateCompleted()); 
      pStatement.setString(5, task.getNote()); 
      pStatement.setInt(6, task.getTaskId().intValue()); 
      pStatement.executeUpdate(); 
     } 
     catch(SQLException e) 
     { 
      e.printStackTrace(); 
     } 
     finally 
     { 
      try{ if(pStatement != null){ pStatement.close(); }} 
      catch(SQLException ex){System.out.println(ex.getMessage());} 
      try{ if(connection != null){ connection.close(); }} 
      catch(SQLException ex){System.out.println(ex.getMessage());} 
     } 
    } 

and runTest:

public void runTest() 
    { 
     try 
     { 
      TaskBusinessLogic logic = new TaskBusinessLogic(); 
      List<Task> list = null; 
      Task task = null;    

      // testing validation 
      try 
      { 
       System.out.println("Checking for exception from null title."); 
       task = new Task(); 
       task.setTaskId(taskId); 
       task.setPriority("high"); 
       logic.updateTask(task); 
       System.out.println("well that didn't work"); 
      } 
      catch(ValidationException e) 
      { 
       System.out.println("Title null check: " + e.getMessage()); 
      } 
      System.out.println(); 
     } 
     catch(ValidationException e){ 
      System.err.println(e.getMessage()); 
     } 
} 

所以,當我嘗試檢查異常,並創建空的標題和優先級的記錄,而不是拋出用戶友好的例外,它拋出:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'Title' cannot be null 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) 
    at java.lang.reflect.Constructor.newInstance(Unknown Source) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) 
    at com.mysql.jdbc.Util.getInstance(Util.java:387) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:934) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3870) 
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3806) 
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2470) 
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2617) 
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2550) 
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861) 
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073) 
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009) 
    at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5094) 
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994) 
    at dataaccesslayer.TaskDaoImpl.addTask(TaskDaoImpl.java:235) 
    at businesslayer.TaskBusinessLogic.addTask(TaskBusinessLogic.java:74) 
    at SimpleTest.runTest(SimpleTest.java:86) 
    at Launcher.main(Launcher.java:21) 

而其他錯誤被發現在友好的通知控制檯。

有沒有辦法解決它?

非常感謝!

+0

我們還需要TaskBusinessLogic.addTask'的'代碼和'SimpleTest.runTest'方法,這顯示在堆棧跟蹤中。 –

+0

我已經添加了這些方法。謝謝! –

回答

0

答案很簡單:驗證title屬性時,validateTask方法不執行任何操作,因爲你已經明確允許空值:

validateString(task.getTitle(), "Title", TITLE_MAX_LENGTH, true); 

true應該是false代替。

無論如何,我建議你重構validateString方法,使其更清晰,更易於閱讀:

private void validateString(String value, String fieldName, int maxLength, boolean isNullAllowed) 
     throws ValidationException 
    { 
     if (value == null) 
     { 
      if (isNullAllowed) 
      { 
       // return; // null permitted, nothing to validate 
      } 
      else 
      { 
       throw new ValidationException(String.format("%s cannot be null", fieldName)); 
      } 
     } 
     else ... 
    } 
+0

這就是原因!非常感謝! –

相關問題