<!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" />
UserDaogit
@Repository public interface UserDao { User qryById(Long id); List<User> pageUser(@Param("name")String name,Page<User> page); int add(User user); }
UserMapper:設置自增主鍵=》useGeneratedKeys="true" keyProperty="id"github
<insert id="add" useGeneratedKeys="true" keyProperty="id"> INSERT INTO USER(<include refid="commonColumns"/>) VALUES (#{id},#{name},#{birthday}) </insert>
注意項:spring
UserService數據庫
@Transactional(rollbackFor = DemoException.class) public Boolean add(User user) throws DemoException{ int count = userDao.add(user); if(count != 1){ throw new DemoException("數據庫更新不爲1"); } LOGGER.info("新增user主鍵id=>{}",user.getId()); if(1 == 1) { throw new DemoException("測試事務事務是否回滾"); } return true; }
UserControllermybatis
@RequestMapping("add") @ResponseBody public Boolean add(User user) throws DemoException{ return userService.add(user); }
User:在set日期方法上加入DateTimeFormat格式化app
@DateTimeFormat(pattern = "yyyy-MM-dd") public void setBirthday(Date birthday) { this.birthday = birthday; }
https://github.com/BAN-WANG/demo測試