首页 > Java > MyBatis获取刚刚插入对象的id

MyBatis获取刚刚插入对象的id

2018年4月19日 admin 发表评论 阅读评论

适用于对于支持自动生成主键的数据库
一、数据库表中ID的设计
id int型 自动递增

二、MyBatis的Mapper
useGeneratedKeys=”true” keyProperty=”id” 是重点

	<insert id="insert" useGeneratedKeys="true" keyProperty="id">
		INSERT INTO rdss2_report(
			report_name,
			componets,
			update_date,
			create_date,
			update_by,
			create_by
		) VALUES (
			#{reportName},
			#{componets},
			#{updateDate},
			#{createDate},
			#{updateBy.id},
			#{createBy.id}
		)
	</insert>

三、Java代码
重要代码如下,在保存完对象后,mybatis会自动把ID反填入对象中,直接获取即可

			rdss2ReportService.save(rdss2Report);
			System.out.println("test:"+rdss2Report.getId()+"-"+rdss2Report.getComponets());
	@RequestMapping(value="/saveReport", method=RequestMethod.POST)
	@ResponseBody
	public void saveReport(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map<String, Object> param) {
		JSONObject jo = new JSONObject();

		try {
			Rdss2Report rdss2Report = new Rdss2Report();
			rdss2Report.setReportName(param.get("title").toString());
			rdss2Report.setComponets(param.get("par").toString());
			rdss2ReportService.save(rdss2Report);
			System.out.println("test:"+rdss2Report.getId()+"-"+rdss2Report.getComponets());

			jo.put("result", "success");
			PrintWriter out = null;
			response.setContentType("application/json");
			out = response.getWriter();
			out.write(jo.toString());

		} catch (Exception e) {
			jo.put("result", "fail");
			PrintWriter out = null;
			response.setContentType("application/json");
			try {
				out = response.getWriter();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			out.write(jo.toString());
			e.printStackTrace();
		}

	}
分类: Java 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.