后期用到hibernate和spring可能就不需要这些了
1.DAOException
package com.neusoft.trainingcenter.hr.utils;
public class DaoException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public DaoException() {
}
public DaoException(String arg0) {
super(arg0);
}
public DaoException(Throwable arg0) {
super(arg0);
}
public DaoException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
2.ServiceException
package com.neusoft.trainingcenter.hr.utils;
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ServiceException() {
}
public ServiceException(String arg0) {
super(arg0);
}
public ServiceException(Throwable arg0) {
super(arg0);
}
public ServiceException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
3.Dao层的demo:
/**
* 增加部门
*
* @param section
* section对象
*/
public void addSection(Section section) {
String sql = "insert into section(" + "snumber," // 标识符
+ "sno," // 部门编号
+ "sname," // 部门名称
+ "stype," // 部门类型
+ "sphone," // 电话
+ "sfax," // 传真
+ "sdes," // 描述
+ "supper," // 上级部门
+ "s_setdate)" // 成立日期
+ "values(s.nextval, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = null;
try {
pstmt = connection.prepareStatement(sql);
pstmt.setString(1, section.getSno());
pstmt.setString(2, section.getSname());
pstmt.setString(3, section.getStype());
pstmt.setString(4, section.getSphone());
pstmt.setString(5, section.getSfax());
pstmt.setString(6, section.getSdes());
pstmt.setString(7, section.getSupper());
pstmt.setDate(8, section.getSdate());
pstmt.executeUpdate();
} catch (SQLException e) {
throw new DaoException("Error on adding section", e);
} finally {
DBUtils.closeStatement(pstmt);
}
}
4:service层demo:
public void addSection(Section section) {
// 数据库连接
// 声明一个部门数据访问对象
// 开始数据库交互
// 调用增加部门方法
// 数据库提交
// 捕捉该过程中异常
Connection conn = null;
try {
conn = DBUtils.getConnection();
SectionDao sectionDao = new SectionDaoImpl(conn);
DBUtils.beginTransaction(conn);
sectionDao.addSection(section);
DBUtils.commit(conn);
} catch (ServiceException e) {
throw e;
} catch (Exception e) {
DBUtils.rollback(conn);
throw new ServiceException("添加部门错误", e);
} finally {
DBUtils.closeConnection(conn);
}
}