编写 MyBatis DAO
实现类
tfw.integration_demo._04_spring_web_mvc._02_crud._03_mybatis_crud._01_manual_dao_way.dao.impl.UserDAO
,在功能验证的基础上添加一定程度的参数检查和预处理,并统一进行异常和收尾处理:
……
public class UserDAO implements I_UserDAO
{
private SqlSessionFactory ssf;
private final String MYBATIS_NAMESPACE = "crud.mybatis.user";
……
public UserDAO(SqlSessionFactory ssf)
{
this.ssf = ssf;
}
……
public int create(User user) throws SQLException
{
if (null == user)
{
return -1;
}
SqlSession session = null;
try
{
final String MYBATIS_OPERATION_ID = "create";
final String MYBATIS_OPERATION =
MYBATIS_NAMESPACE + "." + MYBATIS_OPERATION_ID;
System.out.println(MYBATIS_OPERATION);
session = ssf.openSession();
String strSql = MyBatisSqlHelper.getNamespaceSql(session,
MYBATIS_OPERATION, user);
System.out.println(strSql);
int intJdbcCode = session.insert(MYBATIS_OPERATION, user);
session.commit();
return intJdbcCode;
}
catch (Exception e)
{
throw toSQLException(e);
}
finally
{
finallyOperation(session);
}
}
……
public User findById(Integer itgUserId) throws SQLException
{
SqlSession session = null;
try
{
final String MYBATIS_OPERATION = MYBATIS_NAMESPACE + ".findById";
……
return ……;
}
catch (Exception e)
{
throw toSQLException(e);
}
finally
{
finallyOperation(session);
}
}
……
public List<User> listByName(String strUserName) throws SQLException
{
……
catch (Exception e)
{
throw toSQLException(e);
}
finally
{
finallyOperation(session);
}
}
……
public List<User> listAll() throws SQLException
{
……
catch (Exception e)
{
throw toSQLException(e);
}
finally
{
finallyOperation(session);
}
}
……
public List<User> listByRange(int intStartRowIdx, int intSelectRowCount)
throws SQLException
{
……
catch (Exception e)
{
throw toSQLException(e);
}
finally
{
finallyOperation(session);
}
}
……
public int update(User user) throws SQLException
{
if (null == user)
{
return -1;
}
……
catch (Exception e)
{
throw toSQLException(e);
}
finally
{
finallyOperation(session);
}
}
……
public int discardById(Integer itgUserId) throws SQLException
{
……
catch (Exception e)
{
throw toSQLException(e);
}
finally
{
finallyOperation(session);
}
}
……
public String toString()
{
……
}
……
private SQLException toSQLException(Exception e)
{
if (null == e)
{
return new SQLException("Unknown database operation exception!");
}
else if (e instanceof SQLException)
{
return (SQLException) e;
}
else
{
return new SQLException(e);
}
}
……
private void finallyOperation(SqlSession session)
{
if (null != session)
{
try
{
session.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
说明
/ 注意事项:
- “private final String MYBATIS_NAMESPACE = "crud.mybatis.user";”:
DAO
实现类通过命名空间与
MyBatis
映射文件中的节点发生关联。
- “toSQLException(……);”、“finallyOperation(……);”:
各数据操作方法采用统一的异常处理和收尾处理。