问题描述
我为每个实体都有 Dao 接口。我也为每个资源实现了这些接口,例如 MysqL.MysqL Dao 方法抛出特定的异常,所以我需要在接口层抛出它们,但异常是特定于 MysqL 的,所以我怎么能不把它扔在接口层?或者我需要改变设计吗? 例如,我有 UserDao 接口:
public interface UserDao {
boolean insertUser(Connection connection,User user) throws MysqLEXContainer.MysqLdbnotUniqueException,MysqLEXContainer.MysqLDBLargeDataException,MysqLEXContainer.MysqLDBExecutionException,sqlException;
boolean deleteUser(Connection connection,String login) throws MysqLEXContainer.MysqLDBExecutionException,sqlException;
boolean validateUser(Connection connection,String login,String password) throws MysqLEXContainer.MysqLDBExecutionException,sqlException;
User findUser(Connection connection,sqlException;
boolean updateUser(Connection connection,String newPassword) throws MysqLEXContainer.MysqLDBExecutionException,sqlException;
List<User> findAllUser(Connection connection) throws MysqLEXContainer.MysqLDBExecutionException,sqlException;
}
我已经实现了所有这些,但我只展示了一个
@Override
public boolean insertUser(Connection connection,sqlException {
LOGGER.debug("Insert User Is started");
int rowNum;
ResultSet keys = null;
Connection con;
PreparedStatement statement = null;
try {
String query = QueriesUtil.getQuery("insertUser");
con = connection;
statement = con.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
statement.setString(1,user.getLogin());
statement.setString(2,PasswordUtil.generateStrongPasswordHash(user.getpassword()));
statement.setString(3,user.getUserType());
statement.setString(4,user.getUserEmail());
rowNum = statement.executeUpdate();
keys = statement.getGeneratedKeys();
if (keys.next()) {
user.setUserId(keys.getInt(1));
}
} catch (sqlException e) {
LOGGER.error(e);
if (e.getErrorCode() == 1062) {
throw new MysqLEXContainer.MysqLdbnotUniqueException(String.format("%s %s",user.getLogin(),user.getUserEmail()),e.getCause());
} else if (e.getErrorCode() == 1406) {
throw new MysqLEXContainer.MysqLDBLargeDataException("Data Is too long",e);
}
throw new MysqLEXContainer.MysqLDBExecutionException("Bad execution",e);
} finally {
ConnectionUtil.oneMethodToCloseThemAll(keys,statement,null);
LOGGER.debug("Close all resources");
}
return rowNum > 0;
}
如果我想为 Oracle 实现 dao,我需要向 OracleDb 抛出特定的异常,因此接口的方法签名会有太多的异常。我该如何解决这个问题?
解决方法
我至少可以想到两种方法来实现这一目标:
- 不要在实现中重新抛出 MySQL*异常。只需记录它们。
- 捕获它们并将它们封装为您自己的自定义异常
阅读本文以了解处理异常的一些已知最佳实践:https://dzone.com/articles/9-best-practices-to-handle-exceptions-in-java
,我相信你的方法太老了。几乎所有的开发者都使用某种 ORM,比如 Hibernate、MyBatis 等......
所以,在我看来,你必须使用 ORM。它节省了很多时间。例如,如果您正在使用 Maven 项目,只需将 hibernate 依赖添加到您的 pom.xml
或
您必须编写自定义 Exception 类并使用您的自定义类。