动态sql: sql的内容是变化的,可以根据条件获取到不同的sql语句
主要是where部分发生变化
动态sql的实现:
使用的是mybatis提供的标签:
标签是判断条件的
<!--if标签的使用-->
<select id="selectStudentByIf" resultType="Student">
select id,name,email,age from student where
<if test="age>0">
age> #{age}
</if><!--满足这个if条件时才会把if标签里面的内容拼接到sql语句-->
<if test="id!=0">
and id = #{id}
</if>
</select>
<!--where标签的使用-->
<select id="selectStudentBywhere" resultType="Student">
select id,name,email,age from student
<where>
<if test="age=0">
age>#{age}
</if>
<if test="id!=0">
or id!=#{id}
</if>
</where>
</select>
foreach:循环Java中的数组,list集合的,主要用在sql语句的in语句中
select id,name,email,age from student in <foreach
collection="" item="" open="" close=""></foreach>
参数意义:
<!--foreach的使用
collection:需要遍历的容器,集合list,数组Array
open:最开始的符号(
close:结尾的符号
separator:分隔符
item:表示遍历出来的数据
-->
<select id="selectStudentByforeach" resultType="Student">
select id,name,email,age from student where id in
<foreach collection="list" open="(" close=")" separator="," item="stuid">
#{stuid}
</foreach>
</select>
代码片段:复用一些语句
步骤:
<sql id="StudentByinclude">
select id,name,email,age from student
</sql>
2、include标签把这段代码替换到sql语句中
<select id="selectStudentByinclude" resultType="com.mybatis.damain.Student">
<include refid="StudentByinclude"/>
where id = #{id}
</select>
把数据库连接信息放到一个单独的文件中,和mybatis主配置文件分开
目的是便于修改保存,处理多个数据库的信息
使用步骤:
在resources目录中定义一个属性配置文件:xxxx.properties
在属性配置文件中,定义数据,格式:key = value
key:一般使用 . 做多级目录
例如:
jdbc.mysql.driver = ….
jdbc.diver = ….
配置文件:
jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/bjpowernode?serverTimezone=UTC&&characterEncoding=utf-8
jdbc.username = root
jdbc.password = yky
在mybatis的主配置文件中,使用 指定文件位置 在需要使用值的地方:${key}
<!--指定properties文件的位置,从类路径开始找文件-->
<properties resource="jdbc.properties"></properties>
<!--使用连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
使用步骤:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!--plugin配置分页插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
//分页插件的使用
@Test
public void selectStudentpage(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
PageHelper.startPage(1,3);
List<Student> students = studentDao.selectStudentpageHelper();
students.forEach(stu -> System.out.println(stu));
}