Java SQL null对象引发MySQLIntegrityConstraintViolationException而非自定义异常
使用java.sql 使用以下类对数据库对象执行操作:Java SQL null对象引发MySQLIntegrityConstraintViolationException而非自定义异常,java,mysql,exception,Java,Mysql,Exception,使用java.sql 使用以下类对数据库对象执行操作: public class TaskBusinessLogic { private TaskDao taskDao = null; public TaskBusinessLogic(){ taskDao = new TaskDaoImpl(); } /** * Updates data in the table 'tasks' in the database * @pa
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());}
}
}
和运行测试:
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());
}
}
而其他错误则会在控制台中通过友好通知捕获
有办法解决这个问题吗
非常感谢 答案很简单:
validateTask
方法什么都不做,因为在验证TITLE属性时显式允许空值:
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 ...
}
我们还需要
TaskBusinessLogic.addTask
和SimpleTest.runTest
方法的代码,它们显示在stacktrace中。我已经添加了这些方法。非常感谢。这就是原因!非常感谢你!
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 ...
}