您的位置:首页 > 数据库

mybatis获取插入记录的主键

2017-10-17 20:19 351 查看
在平时的开发中,我们常常需要获取插入数据的主键。在对应的插入语句所在的insert元素中添加以下属性。使用keyProperty指定哪个是主键字段,同时使用useGeneratedKeys指定是否使用数据库的内置生成策略,默认的是false。指定好之后,当插入数据时,mybatis会自动回填所插入记录的主键到对象中。

<!-- keyProperty="id" 指定对象的id属性作为主键-->
<insert id="insertRole" parameterType="com.learn.po.Role" keyProperty="id" useGeneratedKeys="true">
INSERT INTO role(role_name, note) VALUE (#{roleName},#{note})
</insert>


对应mapper接口中的方法

int insertRole(Role role);


测试

public static void main(String[] args) throws IOException {
String path = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(path);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
RoleMapper roleMapper = session.getMapper(RoleMapper.class);
Role role = new Role();
role.setRoleName("admin1");
role.setNote("测试数据1");
roleMapper.insertRole(role);
session.commit();
session.close();
LOGGER.info("插入成功");
LOGGER.info(role.toString());
}


下面是打印的日志:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mybatis 数据库 主键