踩坑记-java mysql 新增获取主键、DIY主键、UUID

java mysql 获取主键、DIY主键、UUID,简单粗暴,代码如下:

mapper.xml

insert id="add" parameterType="com.xuyao.model.User" >
		insert into user
			(
			id,
                        name,
			created_time,
			modified_time
			)
		values
			(
			#{id},
			#{name},
			now(),
			now()
			)

		<selectKey resultType="String" keyProperty="id" order="BEFORE">
			SELECT uuid() id
		</selectKey>
    </insert>
  • selectKey,标签内可以自定义查询方法,DIY ID序号;
  • resultType:返回的类型;
  • keyProperty:model属性名称;
  • order: before,执行之前获取;after,执行之后获取,用于主键自增;

service.java

public User add(User user) throws Exception {
    userMapper.add(user);
    return user;
}
  • 使用传参的实例,并将实例返回;会自动将“ID” 注入到类;

controller

/**
    * 新增用户
    * @param user
    * @param model
    * @param <T>
    * @return
    */
    @RequestMapping(value="", method = RequestMethod.POST, consumes="application/json")
    public <T> Map<String, T> createUser(@RequestBody User user, Model model) {
    	try {
            user = userService.add(user);
            return (Map<String, T>) ResponseUtil.result(HttpStatus.OK, "新增用户成功", user);
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	    return (Map<String, T>) ResponseUtil.result(HttpStatus.INTERNAL_SERVER_ERROR, "新增用户失败. " + e.getMessage(), flowInstance);
	}
    }
posted @ 2019-11-06 21:02  CN徐尧  阅读(604)  评论(0编辑  收藏  举报