Mybatis入门全集

mybatis

一、mybatis入门

1.mybatis需要导入的依赖
<dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--测试依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
2.核心配置文件

​ mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="drldrl521521"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>
3.util工具类

​ 获取sqlSession对象

public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //1.获取SqlSessionFactory对象
            String resource="mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }
}
4.实体类

用lombok注解对实体类set、get、toString、equal等方法进行重写

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private int id;
    private String name;
    private String pwd;
}

lombok依赖

		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
5.Dao接口及Mapper
public interface UserDao {
    //增加用户
    public int addUser(User user);
    //根据id删除用户
    public int deleteUserById(int id);
    //根据Id更新用户信息
    public int updateUserById(User user);
    //查询全部用户
    public List<User> getUserList();
    //根据Id查询用户
    public User getUserById(int id);
	//模糊查询
    public List<User> getUserLike(String value);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--相当于原先JDBC的实现类-->
<!--namespace需要绑定一个相应的Dao/Mapper接口-->
<mapper namespace="com.drl.dao.UserDao">
    <!--
    select查询语句
    "id"相当于接口方法名
    "resultType"是结果集,要全限定名称
    -->
    <select id="getUserList" resultType="com.drl.entity.User">
        select * from user;
    </select>

    <select id="getUserById" parameterType="int" resultType="com.drl.entity.User">
        select * from user where id=#{id}
    </select>
    
    <!--模糊查询-->
    <select id="getUserLike" resultType="com.drl.entity.User">
        select * from user where name like #{value}
    </select>

    <insert id="addUser" parameterType="com.drl.entity.User">
        insert into user values(#{id},#{name},#{pwd})
    </insert>

    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>

    <update id="updateUserById" parameterType="com.drl.entity.User">
        update user set name=#{name},pwd=#{pwd} where id=#{id}
    </update>
</mapper>
6.测试
public class UserDaoTest {

    @Test
    public void test01(){
        //1.获取sqlSession对象
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        //2.方式一:getMapper
        List<User> userList = sqlSession.getMapper(UserDao.class).getUserList();
        for (User user:userList) {
            System.out.println(user);
        }
        //关闭session
        sqlSession.close();
    }

    @Test
    public void test02(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        User user=sqlSession.getMapper(UserDao.class).getUserById(1);
        sqlSession.close();
        System.out.println(user);
    }

    @Test
    public void test03(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        sqlSession.getMapper(UserDao.class).addUser(new User(2,"李四","ls"));
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void test04(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        int res=sqlSession.getMapper(UserDao.class).deleteUserById(2);
        if(res>0)
        {
            System.out.println("删除成功!");
        }
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void test05(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        int res=sqlSession.getMapper(UserDao.class).updateUserById(new User(1,"李四","ls"));
        if(res>0){
            System.out.println("更新成功!");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    
    @Test//模糊查询
    public void test06(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        List<User> list=sqlSession.getMapper(UserDao.class).getUserLike("李");
        for (User user:list){
            System.out.println(user);
        }
    }

}
7.ResultMap
<!--结果集映射-->
    <resultMap id="map" type="User">
        <!--column指数据库中的字段,property指实体类中的属性-->
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="password"/>
    </resultMap>
    <select id="getUserList" resultMap="map">
        select * from user;
    </select>

注意:使用resultMap时,哪个字段不匹配可以改其,相同的则不用再改

<!--结果集映射-->
    <resultMap id="map" type="User">
        <!--column指数据库中的字段,property指实体类中的属性-->
        <result column="pwd" property="password"/>
    </resultMap>
    <select id="getUserList" resultMap="map">
        select * from user;
    </select>
可能遇到的问题

1.maven由于他的约定大于配置,之后写出的配置文件可能无法被导出或生效的问题

The error may exist in com/drl/dao/UserMapper.xml

自己写的配置文件不存在,idea没有检测到

解决方案:

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

2.创建maven项目可能遇到的问题

Information:java: Errors occurred while compiling module 'mybatis-01'
Information:javac 11 was used to compile java sources
Information:Module "mybatis-01" was fully rebuilt due to project configuration/dependencies changes
Information:2021/8/29 10:55 - Build completed with 1 error and 0 warnings in 3 s 953 ms
Error:java: 错误: 不支持发行版本 5

解决方法:

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>13</source>
                    <target>13</target>
                </configuration>
            </plugin>
        </plugins>
 </build>

3.模糊查询

当进行模糊查询时,在传参的字符串中需要加入”%%“进行拼接,

@Test//模糊查询
    public void test06(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        List<User> list=sqlSession.getMapper(UserDao.class).getUserLike("%李%");
        for (User user:list){
            System.out.println(user);
        }

以下模糊查询语句容易被SQL注入,不采用这种方法

<!--模糊查询-->
    <select id="getUserLike" resultType="com.drl.entity.User">
        select * from user where name like #{value}
    </select>

将“%%”写死,只需要传值则不会被注入

<!--模糊查询-->
    <select id="getUserLike" resultType="com.drl.entity.User">
        select * from user where name like "%"#{value}"%"
    </select>

4.已处理“可能遇到问题1”,找不到dao接口的Mapper.xml配置文件

Caused by: 
	java.io.IOException: Could not find resource com.drl.dao.UserMapper.xml

解决方法:

问题可能出在mybatis-config.xml文件中注册mapper时的地址出问题

以下这种是有问题的,mapper中不能用"."来分隔

<mappers>
        <mapper resource="com.drl.dao.UserMapper.xml"/>
    </mappers>

正确如下:

<mappers>
        <mapper resource="com/drl/dao/UserMapper.xml"/> </mappers>

5.当数据库中字段名和实体类中属性名不一致时

当数据库中字段名为"pwd",而实体类中是"password",会使此字段为空
在这里插入图片描述

二、配置优化

1.属性配置优化

db.properties配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8
username=root
password=drldrl521521

不使用db.properties之前的mybatis-congif.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="drldrl521521"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/drl/dao/UserMapper.xml"/>
    </mappers>
</configuration>

在核心配置文件之中引入db.properties之后的mybatis-config.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>

    <!--引入配置文件-->
    <properties resource="db.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="drldrl521521"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/drl/dao/UserMapper.xml"/>
    </mappers>
</configuration>
2.起别名

​ 起别名第一种方式:给每一个类起一个别名

 <!--起别名-->
    <typeAliases>
        <typeAlias type="com.drl.entity.User" alias="User"/>
    </typeAliases>

​ 起别名第二种方式:扫描这个包,别名为首字母小写的类名

<!--起别名-->
    <typeAliases>
        <package name="com.drl.entity"/>
    </typeAliases>
3.日志

在mybatis-config.xml配置文件中配置

【STDOUT_LOGGING】

 <!--引入资源-->
    <properties resource="db.properties"/>

    <!--日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--起别名-->
    <typeAliases>
        <typeAlias type="com.drl.entity.User" alias="User"/>
    </typeAliases>

日志打印在控制台:

Opening JDBC Connection
Created connection 16503286.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@fbd1f6]
==>  Preparing: select * from user; 
==> Parameters: 
<==    Columns: id, name, pwd
<==        Row: 1, 李四, ls
<==        Row: 2, 李五, lw
<==      Total: 2
User(id=1, name=李四, pwd=ls)
User(id=2, name=李五, pwd=lw)

【LOG4J】

加入LOG4J的依赖

    <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>

LOG4J的配置文件

log4j.properties

#设置日志级别,将等级为DEBUG的日志信息输出到console(控制台)和file(文件)这两个目的地
# console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#文件输出的相关设置
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/drl.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM--dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

mybatis核心配置文件中设置log4j

<!--日志-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
4.分页
4.1使用limit分页

​ Mapper接口,使用Map传参

//分页查询,使用map传参
public List<User> getUserByLimit(Map<String ,Object> map);

​ 编写SQL语句,"startIndex"指起始下标(从0开始),"pageSize"指每页都多少数据

<!--分页查询-->
<select id="getUserByLimit" parameterType="map" resultType="User">
     select * from user limit #{startIndex},#{pageSize};
</select>

​ 测试

@Test//分页
    public void test02(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map=new HashMap<>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userByLimit = mapper.getUserByLimit(map);
        for(User user:userByLimit){
            System.out.println(user);
        }
    }
4.2RowBounds(过时)
4.3PageHelper分页插件

三、使用注解开发

​ 使用注解开发时,则不需要UserMapper.xml配置文件,直接在UserMapper接口中使用注解即可,如:

@Select("select * from user where id=#{id}")
    public User getUserById(int id);

​ 在mybatis-config.xml核心配置文件中不需要映射UserMapper.xml配置文件,但是需要绑定UserMapper接口,如:

<!--绑定接口-->
    <mappers>
        <mapper class="com.drl.dao.UserMapper"/>
    </mappers>

​ 用注解不能处理更多复杂事情,比如映射结果集,ResultMap无法实现,若数据库字段名与实体类属性不一致时,会导致某些字段名查询数据为空!
在这里插入图片描述

1.UserMapper注解
public interface UserMapper {

    //增
    @Insert("insert into user values(#{id},#{name},#{pwd})")
    public int addUser(User user);

    //删
    @Delete("delete from user where id=#{id}")
    public int deleteUserById(@Param("id") int id);

    //改
    @Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
    public int updateUserById(User user);

    //查
    @Select("select * from user where id=#{id}")
    public User getUserById(@Param("id") int id);
}
2.测试
@Test//查询
    public void test01(){
        SqlSession sqlSession= MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(2);
        sqlSession.close();
        System.out.println(user);
    }

    @Test//增加
    public void test02(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user=new User(3,"张三","zs");
        int res=mapper.addUser(user);
        System.out.println(res>0?"增加成功!":"增加失败!");
    }

    @Test//删除
    public void test03(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int res=mapper.deleteUserById(3);
        System.out.println(res>0?"删除成功!":"删除失败!");
    }

    @Test//改
    public void test04(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user=new User(2,"张三","zs");
        int res=mapper.updateUserById(user);
        System.out.println(res>0?"修改成功!":"修改失败!");
    }
3.@Param

​ 1.@Param只能放在接口中方法的基本类型参数前,引用类型参数前不能放

​ 2.如果只有一个参数,则可以不加@Param,但是建议加上

​ 3.如果有@Param注解,那么@Param中的名称将会覆盖原来的名称。

​ 比如以下代码将会出错,@Param中的"userId"将"id"覆盖,无法查出

@Delete("delete from user where id=#{id}")
    public int deleteUserById(@Param("userId") int id);

四、复杂查询

学生表
在这里插入图片描述

教师表
在这里插入图片描述

​ 当对单个表查询时很简单,但要查询具有外键的学生信息和对应的教师姓名时可以写出SQL:

select s.id,s.name,s.tid,t.name from student s,teacher t where s.tid=t.id

​ 但如何在mybatis中将其查出?

1.多对一
1.1按照查询嵌套处理

​ 多个学生有一个老师,一个老师教多名学生。

​ 学生角度:多对一,即为关联(association

​ 老师角度:一对多,即为集合(collection

​ 实体类Student

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    private int id;
    private String name;
    private Teacher teacher;
}

​ 实体类Teacher

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {

    private int id;
    private String name;
}

​ StudentMapper接口

public interface StudentMapper {

    public List<Student> getStudent();
}

​ StudentMapper.xml文件

​ 对原本要查的数据返回类型设置为"ResultMap",对象属性用"association"标签。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.drl.dao.StudentMapper">

    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    
    <resultMap id="StudentTeacher" type="com.drl.entity.Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>


    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id=#{id}
    </select>
</mapper>
1.2按照结果嵌套处理

​ StudentMapper接口

public List<Student> getStudent2();

​ StudentMapper.xml文件

<!--按照结果嵌套处理-->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname
        from student s,teacher t
        where s.tid=t.id
    </select>

    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>
2.一对多
2.1按照结果嵌套处理

​ 实体类Student

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    private int id;
    private String name;
    private int tid;
}

​ 实体类Teacher

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {

    private int id;
    private String name;

    //一个老师有多个学校,一对多
    private List<Student> students;
}

​ TeacherMapper接口

public interface TeacherMapper {

    //查询老师的所有学生信息及老师信息
    public Teacher getTeachers(@Param("tid") int id);
}

​ TeacherMapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.drl.dao.TeacherMapper">

    <!--按结果嵌套查询-->
    <select id="getTeachers" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.name tname,t.id tid
        from student s,teacher t
        where s.tid=t.id and t.id=#{tid}
    </select>
    
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--
            复杂的属性要单独处理,对象:association  集合:collection
            javaType="",指定属性的类型
            集合中的泛型,使用ofType获取
        -->
        <collection ofType="Student" property="students">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
</mapper>

结果

Teacher(id=1, name=mary, students=[Student(id=1, name=小明, tid=1), Student(id=2, name=小张, tid=1), Student(id=3, name=小强, tid=1), Student(id=4, name=小李, tid=1), Student(id=5, name=小王, tid=1)])

五、动态SQL

1.If标签

​ 用if标签进行判断然后拼接,用if标签时,要给原本的SQL语句后加一个"where 1=1" 以便后面进行SQL拼接。

​ 另外,用map传参数非常方便,比用实体类传参数更方便!

​ MapperBlog接口

List<Blog> queryBlogIf(Map<String,String> map);

​ MapperBlog.xml文件

<select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from blog where 1=1
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </select>

​ 测试类

@Test
    public void test02(){
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map<String,String> map = new HashMap<>();
        map.put("author","董瑞龙");
        List<Blog> blogList = mapper.queryBlogIf(map);
        for (Blog blog : blogList) {
            System.out.println(blog);
        }

在这里插入图片描述

2.Where标签

​ 上面使用if标签内的SQL后总要加一句"where 1=1"来防止后面SQL出错,若没有"where 1=1",会造成如下错误:

<select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from blog where 1=1
        <if test="title!=null">
            and title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </select>

第一种情况,如果只有title有参数,SQL语句如下,明显出错:

select * from blog where and title=#{title}

第二种情况,如果只有author有参数,SQL语句如下,明显出错:

select * from blog where and author=#{author}

第三种情况,如果title和author都有参数,SQL语句如下,明显出错:

select * from blog where 
and title=#{title} and author=#{author}

综上,为了防止此类问题,可以使用where标签:

<select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <if test="title!=null">
                title=#{title}
            </if>
            <if test="author!=null">
                and author=#{author}
            </if>
        </where>
    </select>

如果title没有参数,author有参数,where标签会自动去掉后面拼接中的"and",SQL如下,不会出错:

select * from blog  where author=#{author}
3.Choose标签

​ 在动态SQL中,想要执行某一个SQL语句而不是全部,则需要使用Chsoose标签。

​ BlogMapper接口

List<Blog> queryBlogChoose(Map<String,Object> map);

​ BlogMapper.xml文件

<select id="queryBlogChoose" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <choose>
                <when test="title!=null">
                    title=#{title}
                </when>
                <when test="author!=null">
                    and author=#{author}
                </when>
                <otherwise>
                    and views=#{views}
                </otherwise>
            </choose>
        </where>
    </select>

使用此标签需注意以下几点:

​ 1.choose标签和where标签一般需结合使用

​ 2.choose相当于"if…else"标签,如果前面的条件能够满足,就不用去判断后面的条件是否能够执行;若前面"when"里的条件没有满足,则执行"otherwise"里的SQL;若三个条件都满足,则执行第一个"when"里的SQL。

4.Set标签

​ 当使用update语句时,可能会对更新字段不确定,则可以使用set标签。

​ BlogMapper接口

int updateBlog(Map<String,Object> map);

​ BlogMapper.xml文件

<update id="updateBlog" parameterType="map">
        update blog
        <set>
            <if test="title!=null">
                title=#{title},
            </if>
            <if test="author!=null">
                author=#{author}
            </if>
            where id=#{id}
        </set>
    </update>
5.SQL片段

​ 在写SQL语句时,会有大量SQL语句片段重复,这时可以使用SQL片段进行复用。

<sql id="if-title-author">
        <if test="title!=null">
            title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </sql>
    
    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>

相关链接:

1.mybatis官方文档地址:https://mybatis.org/mybatis-3/zh/index.html

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值