我正在尝试将一条记录插入我正在使用 Spring 3.0 的数据库中。我没有使用 Hibernate 或任何持久性框架。想知道 DAO 是否正确编写或有什么不同的编写方式:
官员道
public void saveOfficer(Officers officer) {
logger.info("In saveOfficer");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try{
logger.info("Values are "+officer.getUserName()+" "+officer.getPassword()+" "+officer.getfName()+" "+officer.getoName()+" "+officer.getDivisionNo()+" "+officer.getPositionId()+" "+officer.getEmailAdd()+" "+dateFormat.format(officer.getStartDate())+" "+dateFormat.format(officer.getEndDate())+" "+ officer.getGenderId()+" "+officer.getPhoneNo()+" "+dateFormat.format(officer.getDob()));
String sql= "INSERT INTO crimetrack.tblofficers (userName,password, fName, lName, oName, " +
"divisionNo, poisitionId, emailAdd, startDate, endDate, genderId, " +
"phoneNo, dob) VALUES (:userName,:password, :fName, :lName, :oName, :divisionNo, "+
":poisitionId, :emailAdd, :startDate, :endDate, :genderId, " +
":phoneNo, :dob)";
logger.debug("Executing saveOfficer String " + sql);
int count = getJdbcTemplate().update(sql,new MapSqlParameterSource()
.addValue("userName",officer.getUserName())
.addValue("password", officer.getPassword())
.addValue("fName", officer.getfName())
.addValue("lName", officer.getlName())
.addValue("oName", officer.getoName())
.addValue("divisionNo", officer.getDivisionNo())
.addValue("positionId",officer.getPositionId())
.addValue("emailAdd", officer.getEmailAdd())
.addValue("startDate", dateFormat.format(officer.getStartDate()))
.addValue("endDate", dateFormat.format(officer.getEndDate()))
.addValue("genderId", officer.getGenderId())
.addValue("phoneNo",officer.getPhoneNo())
.addValue("dob", dateFormat.format(officer.getDob())));
System.out.println(sql);
logger.info(count +" Rows affected in tblOfficers");
}catch(Exception e){
logger.error("Could not save officer ", e);
}
}
public static class OfficerMapper implements ParameterizedRowMapper<Officers>{
public Officers mapRow(ResultSet rs, int rowNum) throws SQLException {
Officers officer = new Officers();
officer.setUserName(rs.getString("userName"));
officer.setDivisionNo(rs.getInt("divisionNo"));
officer.setDob(rs.getDate("dob"));
officer.setEmailAdd(rs.getString("emailAdd"));
officer.setEndDate(rs.getDate("endDate"));
officer.setfName(rs.getString("fName"));
officer.setGenderId(rs.getString("genderId"));
officer.setlName(rs.getString("lName"));
officer.setoName(rs.getString("oName"));
officer.setPassword(rs.getString("password"));
officer.setPhoneNo(rs.getString("phoneNo"));
officer.setPositionId(rs.getInt("positionId"));
officer.setStartDate(rs.getDate("startDate"));
return officer;
}
}