MyBatis的学习(五):动态Sql语句及其他拓展

MyBatis的学习(五):动态Sql语句及其他拓展

动态Sql

使用的是mybatis的标签,<if>,<\where>,<foreach>

<if>

当test的值为true的时候,会将其包含的sql片段拼接到所在的sql语句中。

语法:

<if test='判断java对象的属性值'>
部分sql语句
</if>

举例子:

  1. 创建dao
   /**
     * 使用if语句
     * @param student
     * @return
     */
    List<Student> selectStuInIf(Student student);
  1. mapper文件
<!--  动态sql的if-->
    <!--第二种模糊查询-->
    <select id="selectStuInIf" resultType="com.liang.entity.Student">
        select id,name,email,age from student
        <!--加上id > 0是为了防止age条件不满足造成语法缺失-->
        where id > 0
        <if test="name != null and name != ''">
            name = #{name}
        </if>
        <if test="age > 0">
            and age > #{age}
        </if>
    </select>
  1. 测试方法
    @Test
    public void testSelectStuInIf(){
        //获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //动态代理获取dao的实体类
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        //执行语句

        Student stu = new Student();
        stu.setName("李四");
        stu.setAge(18);
        List<Student> students = dao.selectStuInIf(stu);
        //输出结果
        for (Student s:students) {
            System.out.println("查询的学生是:"+s);
        }
        sqlSession.close();
    }
  1. 测试结果

image-20220319134328263

<where>

    <!--
    语法格式:<where><if>...</if></where>
    -->
    <select id="selectStuInIf" resultType="com.liang.entity.Student">
        select id,name,email,age from student
        <where>
            <if test="name != null and name != ''">
                name = #{name}
            </if>
            <if test="age > 0">
                and age > #{age}
            </if>
        </where>
    </select>

如果条件符合会直接拼接,如果不符合条件,会去掉多余的拼接或者无效字符。

<foreach>

用来循环Java中的数组。list集合的,主要用在sql的in语句。

语法格式:

        <foreach collection="" item="" open="" separator="">
            
        </foreach>
  • collection:表示接口中的方法参数的类型,如果是数组就用arry,如果是list集合就用list
  • item:自定义的,表示数组和集合成员的变量
  • open:循环开始时候的字符
  • separator:集合成员之间的分隔符

举例子:

  1. dao接口
   /**
     * 使用foreach
     * @param integerList
     * @return
     */
    List<Student> selectStuForEach(List<Integer> integerList);
  1. mapper文件
    <!--foreach的使用-->
    <select id="selectStuForEach" resultType="com.liang.entity.Student">
        select * from student
        <foreach collection="list" item="myid" open="(" close=")" separator=",">
          #{myid}
        </foreach>
    </select>
  1. 测试方法
    @Test
    public void testSelectStuForEach(){
        //获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //动态代理获取dao的实体类
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        //执行语句
        List<Integer> list = new ArrayList<>();
        list.add(1001);
        list.add(1002);
        list.add(1003);
        List<Student> students = dao.selectStuForEach(list);
        //输出结果
        for (Student s:students) {
            System.out.println("查询的学生是:"+s);
        }
        sqlSession.close();
    }
  1. 测试结果

image-20220319142205780

除了可以直接赋值,还可以传入一个对象进行赋值!

其中stu是一个Student的对象。

那么赋值的时候使用stu.id进行赋值!

    <!--foreach的使用-->
    <select id="selectStuForEach" resultType="com.liang.entity.Student">
        select * from student
        <foreach collection="list" item="stu" open="(" close=")" separator=",">
          #{stu.id}
        </foreach>
    </select>

代码片段

主要就是用来复用一些语法:

步骤:

  1. 先定义

  2. 再使用

    <!--定义sql片段-->
    <sql id="studentSql">
        select id,name,email,age from student
    </sql>

    <!--使用sql的复用-->
    <select id="" resultType="com.liang.entity.Student">
        <include refid="studentSql"></include>
        where id in
        <foreach collection="list" item="myid" open="(" close=")" separator=",">
            #{myid}
        </foreach>
    </select>

Mybatis配置文件(了解)

  • <settings>:设置mybatis的行为

  • <typeAliases>:设置别名

  • <environments>:一个数据库的信息配置,环境

  • <transactionManager>:mybatis的事务类型
    type : 表示事务处理的类型

    1. JDBC:JDBC(表示使用的Connection对象的commit,rollback事务处理)
    2. MANAGED:把mybatis的事务处理交给其他容器(一个服务软件,或者一个框架)
  • <dataSource>:表示数据源,连接数据库的
    type:表示数据类型

    1. POOLED表示使用连接池,mybatis会创建PooledDataSources类
    2. UPOOLED:不使用连接池,在每次执行sql语句,先创建连接,执行sql语句,再关闭连接,mybatis会创建一个UPooledSDataSource,管理Connection对象的使用

数据库的属性配置文件

把数据库连接信息放到一个单独的文件中,和mybatis主配置文件分开。

目的是便于修改,保存,处理多个数据库的信息。

  1. 在resources目录下定义一个属性配置文件,xxx.properties

    属性配置文件中,定义数据,格式是key=value

    key:一般使用.做多级目录

    例如:jdbc.driver=com.mysql.jdbc.Driver

  2. 在mybatis的主配置文件中使用<proprtty>指定文件的位置,在需要值的地方,${key}

举例子:

  • 创建properties文件
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/springdb?characterEncoding=UTF8&amp;useSSL=false
jdbc.user = root
jdbc.password = 001204
  • 在主配置文件下的configuration中添加
    <!--指定数据库文件位置-->
    <properties resource="db.properties"/>

image-20220319150329317

  • 代替值
<property name="driver" value="${jdbc.driver}"/>
<!--连接数据库的url-->
<property name="url" value="${jdbc.url}"/>
<!--用户名-->
<property name="username" value="${jdbc.user}"/>
<!--密码-->
<property name="password" value="${jdbc.password}"/>

指定多种mapper

方法一:在mapper中编写

    <mappers>
<!--一个mapper标签指定一个文件的位置,从类路径开始的路径信息-->
        <mapper resource="com/liang/dao/StudentDao.xml"/>
        <mapper resource="com/liang/dao/OrderDao.xml"/>
    </mappers>

方式二:使用包名

    <mappers>
        <!--方式二:使用包名,mapper文件所在的包,这个包的所有xml文件会一次性导入
        要求:1. mapper文件的名称需要和接口名称一样,区分大小写
             2. mapper文件和dao接口需要在同一个目录
        -->
        <package name="com.liang.dao"/>
    </mappers>

PageHelper

帮助进行数据分页的!!!

  1. 在maven的pom文件中加入依赖
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.10</version>
    </dependency>
  1. 在主配置文件的environment前加上
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
  1. dao接口
   /**
     * 使用分页
     * @return
     */
    List<Student> selectAll();
  1. mapper
    <!--分页插件的使用-->
    <select id="selectAll" resultType="com.liang.entity.Student">
        select * from student order by id
    </select>
  1. 测试方法
    @Test
    public void testSelectAll(){
        //获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //动态代理获取dao的实体类
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        //加入分页方法
        //pageNum:第几页,第一页开始
        //pageSize:一页中有多少行数据
        PageHelper.startPage(1,3);
        List<Student> students = dao.selectAll();
        //输出结果
        for (Student s:students) {
            System.out.println("查询的学生是:"+s);
        }
        sqlSession.close();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值