【SSM】MyBatis(七.使用小技巧)

1.#{} 和 ${} 区别

1.1 #{} 和 ${} 区别示例

当我们使用 #{}时
在这里插入图片描述

在这里插入图片描述
当我们改用${}时
在这里插入图片描述

在这里插入图片描述

1.2.区别

#{} 底层使用PreparedStatement,先进行sql语句编译,然后给sql语句的问号传值,没有注入风险。

${} 底层使用Statement,先进行sql语句拼接,然后sql语句编译,存在注入风险。

1.3.使用原则

优先使用 #{},但是如果需要sql语句的的关键字放到sql语句当中,只能使用${}

2.拼接表名

<mapper namespace="com.sdnu.mybatis.mapper.LogMapper">
    <select id="selectAllByTable" resultType="com.sdnu.mybatis.pojo.Log">
        select * from t_log_${date}
    </select>
</mapper>

3.批量删除

Mapper.xml

    <delete id="deleteBatch">
        delete from t_car where id in (${ids})
    </delete>

CarMapper.java

    int deleteBatch(String ids);

Test

    public void testDeleteBatch(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        int count = mapper.deleteBatch("23, 24, 25");
        System.out.println(count);
        sqlSession.commit();
        sqlSession.close();
    }

4.模糊查询

1  like ‘%${brand}%'
2  like concat('%', #{brand}, '%')
3  like concat('%', '${brand}', '%')
4  like "%"#{brand}"%"

5.别名机制

namespace不能使用别名机制。

5.1 采用自己指定的

    <typeAliases>
        <typeAlias type="com.sdnu.mybatis.pojo.Car" alias="aaCar"/>
        <typeAlias type="com.sdnu.mybatis.pojo.Log" alias="bbLog"/>
    </typeAliases>

5.2采用默认别名

    <typeAliases>
        <typeAlias type="com.sdnu.mybatis.pojo.Car"/>
        <typeAlias type="com.sdnu.mybatis.pojo.Log"/>
    </typeAliases>

5.3 包下所有的类自动起别名

 <typeAliases>
	<package name="com.sdnu.mybatis.pojo"/>
 <typeAliases>

6.SQL映射文件的配置方式

● resource:从类路径中加载
● url:从指定的全限定资源路径中加载
● class:使用映射器接口实现类的完全限定类名
● package:将包内的映射器接口实现全部注册为映射器

6.1 class

有两点需要注意:
(1)SQL映射文件和mapper接口放在同一个目录下。
(2)SQL映射文件的名字也必须和mapper接口名一致。

    <mappers>
        <mapper class="com.sdnu.mybatis.mapper.CarMapper"/>
    </mappers>

在这里插入图片描述

6.2 package

如果class较多,可以使用这种package的方式,但前提条件和上一种方式一样。

7.自动生成主键值

CarMapper.xml

<insert id="insertUseGeneratedKeys" useGeneratedKeys="true" keyProperty="id">
  insert into t_car(id,car_num,brand,guide_price,produce_time,car_type) values(null,#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})
</insert>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值