Mybatis的XML配置文件

在复习mybatis的xml配置文件之前,先来复习一下mybatis基础操作之查询。

1.根据ID查询

在员工管理的页面中,当我们进行更新数据时,会点击 “编辑” 按钮,然后此时会发送一个请求到服务端,会根据Id查询该员工信息,并将员工数据回显在页面上。也即页面回显操作。

select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp;
@Mapper
public interface EmpMapper {
    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}")
    public Emp getById(Integer id);
}

 测试类:

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {
    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testGetById(){
        Emp emp = empMapper.getById(1);
        System.out.println(emp);
    }
}

 执行结果:

而在测试的过程中,我们会发现有几个字段(deptId、createTime、updateTime)是没有数据值的,这是为什么呢?

  答:

  • 实体类属性名和数据库表查询返回的字段名一致,mybatis会自动封装。

  • 如果实体类属性名和数据库表查询返回的字段名不一致,不能自动封装。

解决方案 :

  1. 起别名

  2. 结果映射

  3. 开启驼峰命名

起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样

@Select("select id, username, password, name, gender, image, job, entrydate, " +
        "dept_id AS deptId, create_time AS createTime, update_time AS updateTime " +
        "from emp " +
        "where id=#{id}")
public Emp getById(Integer id);

再次执行测试类:

 结果映射

开启驼峰命名(推荐):如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射

驼峰命名规则: abc_xyz => abcXyz

  • 表中字段名:abc_xyz

  • 类中属性名:abcXyz

# 在application.properties中添加:
mybatis.configuration.map-underscore-to-camel-case=true

要使用驼峰命名前提是 实体类的属性 与 数据库表中的字段名严格遵守驼峰命名。

1.2 条件查询

在员工管理的列表页面中,我们需要根据条件查询员工信息,查询条件包括:姓名、性别、入职时间。

通过页面原型以及需求描述我们要实现的查询:

  • 姓名:要求支持模糊匹配

  • 性别:要求精确匹配

  • 入职时间:要求进行范围查询

  • 根据最后修改时间进行降序排序

sql语句:

select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time 
from emp 
where name like '%张%' 
      and gender = 1 
      and entrydate between '2010-01-01' and '2020-01-01 ' 
order by update_time desc;

接口方法:

方式一:

@Mapper
public interface EmpMapper {
    @Select("select * from emp " +
            "where name like '%${name}%' " +
            "and gender = #{gender} " +
            "and entrydate between #{begin} and #{end} " +
            "order by update_time desc")
    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
}

以上方式注意事项:

  1. 方法中的形参名和SQL语句中的参数占位符名保持一致

  2. 模糊查询使用${...}进行字符串拼接,这种方式呢,由于是字符串拼接,并不是预编译的形式,所以效率不高、且存在sql注入风险

方式二(解决sql注入风险)

  • 使用MySQL提供的字符串拼接函数:concat('%' , '关键字' , '%')

@Mapper
public interface EmpMapper {

    @Select("select * from emp " +
            "where name like concat('%',#{name},'%') " +
            "and gender = #{gender} " +
            "and entrydate between #{begin} and #{end} " +
            "order by update_time desc")
    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);

}

执行结果:生成的SQL都是预编译的SQL语句(性能高、安全)

 参数说明:

在上面我们所编写的条件查询功能中,我们需要保证接口中方法的形参名和SQL语句中的参数占位符名相同。当方法中的形参名和SQL语句中的占位符参数名不相同时,就会出现以下问题:

 

2. Mybatis的xml配置文件

Mybatis的开发有两种方式:

  1. 注解

  2. XML

 2.1 xml配置文件规范

使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就是将SQL语句写在XML配置文件中。

在Mybatis中使用XML映射文件方式开发,需要符合一定的规范:

  1. XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)

  2. XML映射文件的namespace属性为Mapper接口全限定名一致

  3. XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致

<select>标签:就是用于编写select查询语句的。

  • resultType属性,指的是查询返回的单条记录所封装的类型

2.2XML配置文件实现

第1步:创建XML映射文件

 第2步:编写XML映射文件

xml映射文件中的dtd约束,直接从mybatis官网复制即可

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="">
 
</mapper>

配置:XML映射文件的namespace属性为Mapper接口全限定名

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">

    <!--查询操作-->
    <select id="list" resultType="com.itheima.pojo.Emp">
        select * from emp
        where name like concat('%',#{name},'%')
              and gender = #{gender}
              and entrydate between #{begin} and #{end}
        order by update_time desc
    </select>
</mapper>

运行测试类,执行结果:

2.3   MybatisX的使用

MybatisX是一款基于IDEA的快速开发Mybatis的插件,为效率而生。

可以通过MybatisX快速定位:

 3.Mybatis动态sql

3.1什么是动态SQL

在页面原型中,列表上方的条件是动态的,是可以不传递的,也可以只传递其中的1个或者2个或者全部。

 而在我们刚才编写的SQL语句中,我们会看到,我们将三个条件直接写死了。 如果页面只传递了参数姓名name 字段,其他两个字段 性别 和 入职时间没有传递,那么这两个参数的值就是null。

此时,执行的SQL语句为:

这个查询结果是不正确的。正确的做法应该是:传递了参数,再组装这个查询条件;如果没有传递参数,就不应该组装这个查询条件。

比如:如果姓名输入了"张", 对应的SQL为:

select *  from emp where name like '%张%' order by update_time desc;

 如果姓名输入了"张",,性别选择了"男",则对应的SQL为:

select *  from emp where name like '%张%' and gender = 1 order by update_time desc;

SQL语句会随着用户的输入或外部条件的变化而变化,我们称为:动态SQL

在Mybatis中提供了很多实现动态SQL的标签,我们学习Mybatis中的动态SQL就是掌握这些动态SQL标签。

3.2 动态SQL-if

<if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。

例如:

原来的sql语句

<select id="list" resultType="com.itheima.pojo.Emp">
        select * from emp
        where name like concat('%',#{name},'%')
              and gender = #{gender}
              and entrydate between #{begin} and #{end}
        order by update_time desc
</select>

动态SQL语句

<select id="list" resultType="com.itheima.pojo.Emp">
        select * from emp
        where
             <if test="name != null">
                 name like concat('%',#{name},'%')
             </if>
             <if test="gender != null">
                 and gender = #{gender}
             </if>
             <if test="begin != null and end != null">
                 and entrydate between #{begin} and #{end}
             </if>
    
        order by update_time desc
</select>

测试方法:

@Test
public void testList(){
    //性别数据为null、开始时间和结束时间也为null
    List<Emp> list = empMapper.list("张", null, null, null);
    for(Emp emp : list){
        System.out.println(emp);
    }
}

结果:

 修改测试方法中的代码,再次进行测试,观察执行情况:

@Test
public void testList(){
    //姓名为null
    List<Emp> list = empMapper.list(null, (short)1, null, null);
    for(Emp emp : list){
        System.out.println(emp);
    }
}

结果:

 报错,控制台显示多了一个and关键字,因为name我们设置为null,但是性别不为空,拼接的时候就多了一个and关键字。

再次修改测试方法中的代码,再次进行测试:

@Test
public void testList(){
    //传递的数据全部为null
    List<Emp> list = empMapper.list(null, null, null, null);
    for(Emp emp : list){
        System.out.println(emp);
    }
}

以上问题的解决方案:使用<where>标签代替SQL语句中的where关键字

  • <where>只会在子元素有内容的情况下才插入where子句,而且会自动去除子句的开头的AND或OR

<select id="list" resultType="com.itheima.pojo.Emp">
        select * from emp
        <where>
             <!-- if做为where标签的子元素 -->
             <if test="name != null">
                 and name like concat('%',#{name},'%')
             </if>
             <if test="gender != null">
                 and gender = #{gender}
             </if>
             <if test="begin != null and end != null">
                 and entrydate between #{begin} and #{end}
             </if>
        </where>
        order by update_time desc
</select>

再次运行:

 类似:

  • <set>:动态的在SQL语句中插入set关键字,并会删掉额外的逗号。(用于update语句中)

小结

  • <if>

    • 用于判断条件是否成立,如果条件为true,则拼接SQL

    • 形式:

      <if test="name != null"> … </if>
  • <where>

    • where元素只会在子元素有内容的情况下才插入where子句,而且会自动去除子句的开头的AND或OR

  • <set>

    • 动态地在行首插入 SET 关键字,并会删掉额外的逗号。(用在update语句中)

3.3 动态SQL-foreach 

案例:员工删除功能(既支持删除单条记录,又支持批量删除)

sql语句:

delete from emp where id in (1,2,3);

 Mapper接口:

@Mapper
public interface EmpMapper {
    //批量删除
    public void deleteByIds(List<Integer> ids);
}

XML映射文件:

  • 使用<foreach>遍历deleteByIds方法中传递的参数ids集合

<foreach collection="集合名称" item="集合遍历出来的元素/项" separator="每一次遍历使用的分隔符" 
         open="遍历开始前拼接的片段" close="遍历结束后拼接的片段">
</foreach>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
    <!--删除操作-->
    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
</mapper> 

执行的SQL语句:

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Mybatis是一款优秀的持久层框架,其核心配置文件是用于配置Mybatis的各种参数以及SQL语句映射关系的xml文件。以下是一个简单的Mybatis核心配置文件xml的示例: ```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> <typeAliases> <typeAlias type="com.example.User" alias="User"/> </typeAliases> <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/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/example/UserMapper.xml"/> </mappers> </configuration> ``` 上述xml文件中主要包含以下三个部分: 1. **typeAliases**:用于为Java类型建立别名,可以简化后续的SQL语句映射操作。 2. **environments**:定义Mybatis使用的环境,包括事务管理器和数据源等。 3. **mappers**:定义映射文件,即SQL语句与Java方法的映射关系。在示例中,`UserMapper.xml`文件定义了SQL语句与Java接口的映射关系。 这是一个简单的Mybatis核心配置文件xml示例,实际应用中可能会更加复杂,需要根据具体情况进行配置。 ### 回答2: MyBatis核心配置文件是一个重要的配置文件,用于定义和配置MyBatis的全局属性和设置。 在MyBatis核心配置文件中,第一个标签是`<configuration>`,它是整个配置文件的根元素。在该标签中可以配置一些全局通用的设置,比如类型别名、插件等。可以使用`<typeAliases>`标签来定义别名,使得在Mapper映射文件中可以使用别名来代替类的全限定名。插件可以通过自定义拦截器来对SQL语句进行增强或自定义处理。 接下来是`<environments>`标签,用于配置MyBatis的数据库环境。在该标签中可以配置多个`<environment>`子标签,每个子标签代表一个数据库环境,包括数据库连接池、事务管理器等。可以通过`<transactionManager>`标签配置事务管理器,通过`<dataSource>`标签配置数据库连接池。 紧接着是`<mappers>`标签,用于配置Mapper映射器。可以使用`<mapper>`子标签来引入Mapper映射文件,可以配置多个`<mapper>`标签。在Mapper映射文件中定义了与数据库交互的SQL语句和对应的映射关系。 除了上述标签外,还有一些其他的全局配置,比如日志输出方式、延迟加载等。可以通过`<properties>`标签定义一些全局的配置属性,并通过`${}`引用这些属性。 总之,MyBatis核心配置文件MyBatis框架中的一个重要组成部分,通过配置该文件,可以定义和配置一些全局的属性和设置,使得MyBatis能够正常运行并与数据库交互。 ### 回答3: Mybatis的核心配置文件是一个XML文件,用于配置与数据库相关的信息和Mybatis框架的各种功能。 首先,核心配置文件需要指定数据库的连接信息,包括数据库的URL、驱动程序类名、用户名和密码等。这些信息使得Mybatis能够和数据库建立连接,并执行SQL语句。 其次,核心配置文件还包括映射器(Mapper)的注册信息。映射器是一个用于定义数据库操作的接口,通过将接口与数据库的SQL语句进行映射,实现了Java方法和数据库操作的关联。核心配置文件会定义多个映射器的路径,用于告诉Mybatis在哪里可以找到这些映射器的定义。 另外,核心配置文件还可以配置一些全局属性和插件。全局属性可以被映射器中定义的SQL语句引用,用于动态地生成SQL语句。插件可以为Mybatis提供额外的功能,比如自定义拦截器、日志记录等。 在核心配置文件中,还可以定义数据库连接池的配置、缓存的配置、事务管理器的配置等。这些配置项可以根据实际需求进行调整,以满足特定的性能要求和业务需求。 总之,Mybatis的核心配置文件是一个重要的配置文件,用于定义数据库连接信息、映射器的路径和其他配置项。通过对核心配置文件的配置,可以实现与数据库的连接、SQL语句的映射以及其他数据库相关的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值