一、mapper.xml基本配置概述

在 MyBatis 中,mapper.xml 文件是用来编写 SQL 语句的重要配置文件,通过它可以完成数据查询、插入、更新、删除等数据库操作。本文将介绍 mapper.xml 的基本配置方法。

二、mapper.xml 基本配置示例

下面是一个简单的 mapper.xml 文件示例:

1. 命名空间(namespace)

在 mapper.xml 文件的开头,我们需要为该文件指定一个命名空间(namespace)。命名空间的作用是与接口文件相对应,它指定了接口文件的全限定名。例如:


<?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">
<mapper namespace="com.example.mapper.UserMapper">
    
</mapper>

其中,`namespace` 属性的值为接口文件`UserMapper`的全限定名。

2. sql语句的编写

在 mapper.xml 文件中,可以使用各种 SQL 语句,例如查询语句、插入语句、更新语句、删除语句等。


<select id="getUserById" resultType="com.example.entity.User">
    SELECT * FROM user WHERE id = #{id}
</select>

<insert id="insertUser" parameterType="com.example.entity.User">
    INSERT INTO user(username, password) VALUES (#{username}, #{password})
</insert>

<update id="updateUser" parameterType="com.example.entity.User">
    UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}
</update>

<delete id="deleteUserById" parameterType="int">
    DELETE FROM user WHERE id = #{id}
</delete>

上述示例中,`select` 标签表示查询语句,`insert` 标签表示插入语句,`update` 标签表示更新语句,`delete` 标签表示删除语句。`id` 属性为方法名,`resultType` 属性表示查询结果类型,`parameterType` 属性表示方法参数类型。

3. resultMap映射配置

在实际开发中,我们通常会将查询结果映射到 POJO 类中,这时可以使用 resultMap 进行结果映射配置。


<select id="getUserById" resultMap="userResultMap">
    SELECT * FROM user WHERE id = #{id}
</select>

<resultMap id="userResultMap" type="com.example.entity.User">
    <id property="id" column="id"/>
    <result property="username" column="username"/>
    <result property="password" column="password"/>
</resultMap>

上述示例中,`select` 标签的 `resultMap` 属性指向了一个 id 为 `userResultMap` 的 resultMap 配置块,该配置块定义了如何将查询结果映射到 User 类的各个属性中。

4. 引入外部配置文件

为了提高配置文件的可读性和可维护性,我们可以将 mapper.xml 文件拆分为多个文件,并通过引入外部配置文件来包含它们。

下面是一个示例:

mapper.xml 文件:


<?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">
<mapper namespace="com.example.mapper.UserMapper">
    <include file="query.xml"/>
    <include file="insert.xml"/>
    <include file="update.xml"/>
    <include file="delete.xml"/>
</mapper>

query.xml 文件:


<resultMap id="userResultMap" type="com.example.entity.User">
    <id property="id" column="id"/>
    <result property="username" column="username"/>
    <result property="password" column="password"/>
</resultMap>

<select id="getUserById" resultMap="userResultMap">
    SELECT * FROM user WHERE id = #{id}
</select>

通过使用 `` 标签,可以将外部的 query.xml、insert.xml、update.xml 和 delete.xml 文件引入到 mapper.xml 文件中,这样可以提高配置文件的可读性和维护性。

以上就是 mapper.xml 的基本配置方法,在实际开发中,可以根据具体需求进行灵活运用。