mybatis中琐碎的小知识点

1、插入时的主键回填问题
答:只要在insert的sql语句中,将属性useGeneratedKeys设置为true和设置keyProperty即可,其中useGeneratedKeys,代表启动获取主键功能,keyProperty,代表将生成的主键放在哪一个属性中

2、自定义主键问题
答:在insert的sql语句中添加如下语句:

<insert id="addRole" parameterType="pojo.Role">
        <selectKey order="BEFORE" keyProperty="id" resultType="int">
            select if(max(id=null,1,max(id)+1)) from t_role
        </selectKey>
        insert into t_role values (#{id},#{roleName},#{note})
    </insert>

其中,order定义是在sql执行前还是后面,keyProperty代表将查到的id放在哪个属性,resultType代表id是什么类型

3、mybatis中的sql元素怎么用
用途:主要将一些重复使用的sql进行抽出来,然后以变量的方式再引入sql语句中,示例如下

初始sql为:select id,role_name as roleName,note from t_role
使用sql元素:
    <sql id = "roleCols">
          id,role_name as roleName,note
    <sql>
此时变为:
     select <include refid="roleCols"/> from t_role
该sql语句与上方的sql语句等价

猜你喜欢

转载自blog.csdn.net/q1937915896/article/details/88078246