<insert id="addRole" parameterType="SysRole" useGeneratedKeys="true" keyProperty="roleId" keyColumn="role_id">
insert into t_sys_role( name,status )
values( #{name,jdbcType=VARCHAR}, <span> </span>#{status,jdbcType=VARCHAR}, )
</insert>
</code>
注:
1、添加记录能够返回主键的关键点在于需要在<insert>标签中添加以下三个属性<insert useGeneratedKeys="true" keyProperty="id" keyColumn="id"></insert>。
useGeneratedKeys:必须设置为true,否则无法获取到主键id。
keyProperty:设置为POJO对象的主键id属性名称。
keyColumn:设置为数据库记录的主键id字段名称
2、新添加主键id并不是在执行添加操作时直接返回的,而是在执行添加操作之后将新添加记录的主键id字段设置为POJO对象的主键id属性
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:config/spring-core.xml","classpath:config/spring-web.xml"})
public class TestDao{
@Autowired
SysRoleDao roleDao;
@Test
public void test() {
SysRole role=new SysRole();
role.setName("admin10");
role.setStatus(1);
System.out.println("返回结果:"+roleDao.addRole(role));
System.out.println("主键id:"+role.getRoleId());
}
}