mybatis获取插入记录的主键
2017-10-17 20:19
351 查看
在平时的开发中,我们常常需要获取插入数据的主键。在对应的插入语句所在的insert元素中添加以下属性。使用keyProperty指定哪个是主键字段,同时使用useGeneratedKeys指定是否使用数据库的内置生成策略,默认的是false。指定好之后,当插入数据时,mybatis会自动回填所插入记录的主键到对象中。
对应mapper接口中的方法
测试
下面是打印的日志:
<!-- 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()); }
下面是打印的日志:
相关文章推荐
- 利用Java的MyBatis框架获取MySQL中插入记录时的自增主键
- mybatis如何获取oracle新插入数据记录的主键?
- mybatis如何获取oracle新插入数据记录的主键?
- Mybatis获取插入记录的自增长ID
- Mybatis获取插入记录的自增长ID
- Mybatis获取插入记录的自增长ID
- JDBC( 八) 获取插入记录的主键。
- MyBatis插入时候获取自增主键方法
- Mybatis如何在插入操作后获取主键的ID值
- mybatis获取当前插入记录的id
- mybatis新增数据,数据VO获取db记录主键
- mybatis获取插入的语句主键(自增主键)
- 数据库中插入一条记录后获取主键id
- Mybatis获取刚刚插入的一条数据的主键值(插入时主键未制定数据库支持主键自增)
- 使用mybatis的insert语句插入数据的时候,获取插入数据的主键id
- mybatis获取当前插入记录的id
- 用mybatis实现返回刚插入表数据记录的主键值id
- MyBatis获取插入记录的自增长字段值
- 初学JDBC,获取插入记录的主键、执行批量操作
- java获取使用mybatis刚插入数据的主键id