MyBatis参数与SqlMapConfig.xml核心配置示例详细说明的重点在于把前置条件、操作顺序和容易误判的地方分清楚。
int、double、String、long等。框架提供了简写方式,例如 java.lang.Integer 可以简写为 int、integer、Int、Integer 等。

<select id="findById" parameterType="int" resultType="User"> select * from user where id = #{id}</select>直接使用实体类的全路径或别名:
<insert id="insert" parameterType="com.qcbyjy.domain.User"> insert into user (username) values (#{username})</insert>当需要传递多个实体类参数时,可以创建包装类:
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>int、double、long、String等:
<select id="findByCount" resultType="int"> select count(*) from user</select>
直接返回实体类对象:
<select id="findById" resultType="User"> select * from user where id = #{id}</select>当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配置说明:
方式一:直接在配置文件中定义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>MyBatis内置了类型别名注册,我们自己也可以注册别名:
<typeAliases> <!-- 针对com.qcbyjy.domain包下的所有类,使用类名做为别名 --> <package name="com.qcbyjy.domain"/></typeAliases>
配置后,在Mapper.xml中可以直接使用类名(不区分大小写):
<select id="findAll" resultType="user"> select * from user</select>