1.使用generator自动生成dto、entity、mapper.xml
2.HTTP、POST使用实体类BEAN交互数据
@RequestMapping(value = "/api/testB3", method = RequestMethod.POST)
public Object testB3(HttpServletRequest request, HttpServletResponse response, @RequestBody User user)
throws Exception {
logger.info("------testB3------");
return user;
}
POSTMAN测试:
字段名必须和User实体类中一致否则:
原来使用的模式
@RequestMapping(value = "/api/testB4", method = RequestMethod.POST)
public Object testB4(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject jsonParam)
throws Exception {
logger.info("------testB4------");
return jsonParam;
}
postman测试:
3.增加数据库操作示例
增加相应的接口类UserService、UserServiceimpl
插入数据:
代码:
@RequestMapping(value = "/api/testB5", method = RequestMethod.POST)
public Object testB5(HttpServletRequest request, HttpServletResponse response, @RequestBody User user)
throws Exception {
logger.info("------testB5------");
return userService.insert(user);
}
测试:
自动生成的XML:
数据库结果:
查询数据:
由于自动没有生成查询全部数据的接口:
xml手工添加
<select id="findAll" resultMap="BaseResultMap">
select * from user
</select>
手工添加:
注意多记录返回类型List<Map>,否则报错
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
@RequestMapping(value = "/api/testB6", method = RequestMethod.POST)
public Object testB6(HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("------testB6------");
return userService.findAll();
}
测试效果:
使用自动生成的实体VO类,增加数据库表中原来没有的字段:
实体类中手工添加代码:
@RequestMapping(value = "/api/testB7", method = RequestMethod.POST)
public Object testB7(HttpServletRequest request, HttpServletResponse response, @RequestBody User user)
throws Exception {
logger.info("------testB7------");
logger.info("sign = "+user.getSign());
return userService.insert(user);
}
增加字段后不影响SQL操作。
更新数据:
int updateByPrimaryKey(User record);
public int updateByPrimaryKey(User record) {
// TODO Auto-generated method stub
return userMapper.updateByPrimaryKey(record);
}
@RequestMapping(value = "/api/testB8", method = RequestMethod.POST)
public Object testB8(HttpServletRequest request, HttpServletResponse response, @RequestBody User user)
throws Exception {
logger.info("------testB8------");
return userService.updateByPrimaryKey(user);
}
做事务封装:
XML新增:
<insert id="insertAll" parameterType="com.gg.lxz.db.entity.User">
<!--
WARNING - @mbg.generated
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Wed Jul 08 14:42:18 CST 2020.
-->
insert into user (username, password)
values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR})
</insert>
两步操作的服务方法:
@RequestMapping(value = "/api/testB9", method = RequestMethod.POST)
public Object testB9(HttpServletRequest request, HttpServletResponse response, @RequestBody User user)
throws Exception {
logger.info("------testB9------");
return userService.insertAll(user);
}
测试:
结果第一次插入成功,第二次异常,最终第一条插入记录回滚:
、