将Service层交给事务去管理,beans.xml配置如下:
如果需要返回自增字段,插入过程如下:
public int createHousedoor(Housedoor housedoor) {
int newId = 0;
final Housedoor TmpDoor = housedoor;
String issueDateStr = housedoor.getF_IssueDateStr();
Date issueDate = null;
if (issueDateStr != null) {
try {
issueDate = sdf.parse(issueDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
final Date _date = issueDate;
KeyHolder keyholder = new GeneratedKeyHolder();
final String insertsql = "insert into t_housedoor(F_TownId,F_Community,F_PropertyName,F_HouseEstate,F_BuildingNum,F_CellNum,F_RoomNum,F_DoorNum,F_MarkSizeId,F_SourceTypeId,F_Contact,F_Telephone,F_OldAddress,F_Remark,F_UserId,F_OptDate,F_bImport,F_CardId,F_IssueDate,F_Address) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
int countt = 0;
countt = jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
// TODO Auto-generated method stub
PreparedStatement preState = con.prepareStatement(insertsql,
PreparedStatement.RETURN_GENERATED_KEYS);
preState.setString(1, TmpDoor.getF_TownId());
preState.setString(2, TmpDoor.getF_Community());
preState.setString(3, TmpDoor.getF_PropertyName());
preState.setString(4, TmpDoor.getF_HouseEstate());
preState.setString(5, TmpDoor.getF_BuildingNum());
preState.setString(6, TmpDoor.getF_CellNum());
preState.setString(7, TmpDoor.getF_RoomNum());
preState.setString(8, TmpDoor.getF_DoorNum());
preState.setInt(9, TmpDoor.getF_MarkSizeId());
preState.setInt(10, TmpDoor.getF_SourceTypeId());
preState.setString(11, TmpDoor.getF_Contact());
preState.setString(12, TmpDoor.getF_Telephone());
preState.setString(13, TmpDoor.getF_OldAddress());
preState.setString(14, TmpDoor.getF_Remark());
preState.setString(15, TmpDoor.getF_UserId());
preState.setDate(16, new java.sql.Date(new Date().getTime()));
preState.setInt(17, TmpDoor.getF_bImport());
preState.setString(18, TmpDoor.getF_CardId());
if (_date == null)
preState.setDate(19, null);
else
preState.setDate(19, new java.sql.Date(_date.getTime()));
preState.setString(20, TmpDoor.getF_Address());
return preState;
}
}, keyholder);
if (countt == 1) {
newId = (int) keyholder.getKey().longValue();
}
return newId;
}
上述代码中标红的地方一定不能让jdbcTemplate自己去获取,否则事务不起作用。
另外需要注意的是,在service的方法中调用dao层的方法,dao层方法中不能捕获异常,否则service端检测不到异常事务无法回滚