一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

MyBatis参数与SqlMapConfig.xml核心配置示例详细说明

时间:2026-08-07 10:25:50 编辑:袖梨 来源:一聚教程网

MyBatis参数与SqlMapConfig.xml核心配置示例详细说明的重点在于把前置条件、操作顺序和容易误判的地方分清楚。

一、parameterType参数类型

1.1 简单数据类型

int、double、String、long等。框架提供了简写方式,例如 java.lang.Integer 可以简写为 int、integer、Int、Integer 等。

MyBatis参数与SqlMapConfig.xml核心配置示例详解

<select id="findById" parameterType="int" resultType="User">    select * from user where id = #{id}</select>

1.2 POJO对象类型

直接使用实体类的全路径或别名:

<insert id="insert" parameterType="com.qcbyjy.domain.User">    insert into user (username) values (#{username})</insert>

1.3 POJO包装对象类型

当需要传递多个实体类参数时,可以创建包装类:

public class QueryVo implements Serializable {    private String name;    private User user;    private Role role;    // getter/setter省略}<select id="findByVo" parameterType="com.qcbyjy.domain.QueryVo" resultType="User">    select * from user where username = #{user.username}</select>

二、resultType结果类型

2.1 返回简单数据类型

int、double、long、String等:

<select id="findByCount" resultType="int">    select count(*) from user</select>

2.2 返回POJO数据类型

直接返回实体类对象:

<select id="findById" resultType="User">    select * from user where id = #{id}</select>

三、resultMap结果映射

当SQL查询字段名和POJO的属性名不一致时,可以通过 resultMap 建立映射关系:

<!-- 使用resultMap --><select id="findUsers" resultMap="userMap">    select id _id, username _username, birthday _birthday,            sex _sex, address _address from user</select><!-- 配置resultMap --><resultMap id="userMap" type="com.qcbyjy.domain.User">    <result property="id" column="_id"/>    <result property="username" column="_username"/>    <result property="birthday" column="_birthday"/>    <result property="sex" column="_sex"/>    <result property="address" column="_address"/></resultMap>

resultMap配置说明:

  1. property:JavaBean中的属性名
  2. column:数据库表中的字段名

四、SqlMapConfig.xml核心配置

4.1 properties标签管理数据库信息

方式一:直接在配置文件中定义property标签

<properties>    <property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>    <property name="jdbc.url" value="jdbc:mysql:///mybatis_db"/>    <property name="jdbc.username" value="root"/>    <property name="jdbc.password" value="root"/></properties>

方式二(推荐):读取外部jdbc.properties文件

创建 jdbc.properties 文件:

jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql:///mybatis_dbjdbc.username=rootjdbc.password=root

在 SqlMapConfig.xml 中引入:

<properties resource="jdbc.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>

4.2 typeAliases类型别名

MyBatis内置了类型别名注册,我们自己也可以注册别名:

<typeAliases>    <!-- 针对com.qcbyjy.domain包下的所有类,使用类名做为别名 -->    <package name="com.qcbyjy.domain"/></typeAliases>

配置后,在Mapper.xml中可以直接使用类名(不区分大小写):

<select id="findAll" resultType="user">    select * from user</select>

总结

热门栏目