目录
问题1:使用mybatis,Dao层insert、delete、update方法的返回值
问题2:mybaits的useGeneratedKeys属性
1、mybaits中可添加useGeneratedKeys属性的地方
问题1:使用mybatis,insert、delete、update、select方法的返回值(int)
insert、delete、update的返回有两种情况
- 返回n(n >= 0),n为受影响的行数
- 异常
补充:select方法的返回值
- Entity
- 查到,不为null
- 没查到,为null
- List<Entity>
- 查到,list.size() > 0
- 没查到,list.size() == 0, 但是list != null
问题2:mybaits的xianguseGeneratedKeys属性
1、mybaits中可添加useGeneratedKeys属性的地方
- xml映射器
- 接口(注解)映射器
- 全局配置文件中的setting元素
xml映射器:
(insert and update only) This tells MyBatis to use the JDBC getGeneratedKeys method to retrieve keys generated internally by the database (e.g. auto increment fields in RDBMS like MySQL or SQL Server). Default: false.
————————————————
使用JDBC的getGeneratedKeys的方法来获取的,而且只有insert
和update
生效。
接口映射器:
@Options This annotation provides access to the wide range of switches and configuration options that are normally present on the mapped statement as attributes
————————————————
@Options注解提供了对广泛开关和配置选项的访问,这些开关和配置选项通常作为属性出现在映射语句中,就是也就是说这个配置了后,它会直接作为属性出现在映射语句中,会覆盖setting中的配置
setting:
Allows JDBC support for generated keys. A compatible driver is required. This setting forces generated keys to be used if set to true, as some drivers deny compatibility but still work (e.g. Derby). Default: false.
————————————————
对于支持自动生成记录主键的数据库,如:MySQL,SQL Server,此时设置useGeneratedKeys参数值为true,在执行添加记录之后可以获取到数据库自动生成的主键ID。
2、优先级
xml映射器中的useGeneratedKeys只对自己生效
接口映射器 > setting,同时这setting只对接口映射器生效,接口映射器同样只对自己有效
3、useGeneratedKeys属性的作用
在项目中经常需要获取到插入数据的主键来保障后续操作,数据库中主键一般我们使用自增或者uuid()的方式自动生成。useGeneratedKeys属性可以让我们获取到主键
4、如何使用useGeneratedKeys
<insert id="createOrder" useGeneratedKeys="true" keyProperty="id">
insert into t_order(serial) values (#{serial})
</insert>
需要配合keyProperty属性,keyProperty对应接收主键值的对象的字段,即Dao接口方法中的参数对象