欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

SSM(5)(动态 sql<if>,<where>,返回主键值)

最编程 2024-10-11 15:56:14
...

返回主键值:

方法一:

useGeneratedKeys 为ture 声明 返回主键

keyProperty 表示要返回的值 封装到对象的属性中

但是这一种方法不支持Orcal数据库。

    <insert id="save2" parameterType="com.findyou.entity.User" useGeneratedKeys="true" keyProperty="id">
        insert into user(username) values(#{username});
    </insert>

方法二:

selectKey标签支持所有的数据库

order  表示先后顺序
keyProperty  给到对象的哪个属性
keyCoLum 数据库里面哪个字段是主键
resuLtType  返回值的类型

    <insert id="save3" parameterType="com.findyou.entity.User">
        <selectKey order="AFTER" keyProperty="id" resultType="int" keyColumn="id">
            select LAST_INSERT_ID();
        </selectKey>
        insert into user(username) values(#{username});
    </insert>

动态sql:

 <if>标签

if标签里面的属性 test= "条件",当这个条件满足的时候才会进去。

<where>标签

where标签解决and等拼接的问题。

但需要注意的是:where标签只会 智能的去除(忽略)首个满足条件语句的前缀。所以建议在使用where标签时,每个语句最好写上 and 前缀或者 or 前缀。

注意的是:

Integer 类型空的情况下是 null, int类型的空是0。因此在判断的时候写的是 != null and != ''

    <!--动态sql-->
    <select id="findByIdAndUsernameIf" resultType="user" parameterType="user">
        select * from user
        <where>
            <if test="id != null and id != ''">
                and id = #{id}
            </if>
            <if test="username != null">
                and username = #{username}
            </if>

        </where>
    </select>

推荐阅读