insert操作时,需要获取主键ID。在mybatis执行完insert操作后,我传入到insert()里面的那个entity对象,就有ID值了, mybatis自动给赋值上了! 我一直用一个变量(id)接收,只能接收到影响的行数!
正确的获取方法:
1 public Integer save(){ 2 UserInfo entity = new UserInfo(); 3 ... 4 entity.setUpdateTime(new Date()); 5 userInfoDAO.insert(entity); 6 return entity.getId(); 7 }
错误的获取方法:
1 public Integer save(){ 2 UserInfo entity = new UserInfo(); 3 ... 4 entity.setUpdateTime(new Date()); 5 Integer id = userInfoDAO.insert(entity); 6 return id; 7 }
mybatis中的insert写法
<insert id="insert" parameterType="com.xxx.xxx.entity.xxx" useGeneratedKeys="true" keyProperty="id"> INSERT INTO comment_library <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> ... </trim> VALUES <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> #{id}, </if> ... </trim> </insert>