1. Idea中设置Mybatis核心配置文件的模板
File And Code Templates
<?xml version="1.0" encoding="UTF-8" ?> <!--Mybatis配置文件中的约束--> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource=""></properties> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <typeAlias type="" alias=""></typeAlias> </typeAliases> <!--设置连接数据库的环境--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value=""/> <property name="url" value=""/> <property name="username" value=""/> <property name="password" value=""/> </dataSource> </environment> </environments> <!--引入映射文件--> <mappers> <mapper resource=""/> </mappers> </configuration>
2. Idea中设置映射文件的模板
<?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=""> </mapper>
3. Mybatis获取参数值的两种方式#{}和${}
Mybatis获取参数值的两种方式:${}、#{};
${}的本质是字符串拼接,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;
#{}的本质是占位符赋值,若为字符串类型或日期类型的字段进行赋值时,会自动添加单引号;
3.1 mapper接口方法的参数为单字面量类型
<select id="getUserById" resultType="User"> select * from user where id = #{id} <!--select * from user where id = '${id}'--> </select>
3.2 mapper接口方法的参数为多字面量类型
List<User> checkLogin(@Param("name") String name, @Param("password") String password);
<select id="checkLogin" resultType="User"> <!--select * from user where name = #{name} and password = #{password};--> select * from user where name = #{arg0} and password = #{arg1}; </select>
当存在多个参数时,Mybatis会将这些参数放在一个map集合中,以两种方式进行存储:
a> 以arg0、arg1、...为键,以参数为值;
b> 以param1、param2...为键,以参数为值;
c> 手动将参数放到map中存储,将map作为参数传入;
d> 将参数存放到实体类对象中,将实体类作为参数传入;
e> 使用@Param注解命名参数;
3.3 @Param源码解析
public Object getNamedParams(Object[] args) { final int paramCount = names.size(); if (args == null || paramCount == 0) { return null; } else if (!hasParamAnnotation && paramCount == 1) { return args[names.firstKey()]; } else { final Map<String, Object> param = new ParamMap<Object>(); int i = 0; for (Map.Entry<Integer, String> entry : names.entrySet()) { param.put(entry.getValue(), args[entry.getKey()]); // add generic param names (param1, param2, ...) final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1); // ensure not to overwrite parameter named with @Param if (!names.containsValue(genericParamName)) { param.put(genericParamName, args[entry.getKey()]); } i++; } return param; } }
4. Mybatis的各种查询功能
- 查询一个实体类对象:使用实体类进行接收;
- 查询多个结果:使用集合进行接收;
- 查询聚合函数:Mybatis提供的类型别名的映射:


- 查询一条结果转为Map集合;Map<String,Object>
- 查询多条结果转为Map集合; @MapKey("id") Map<String,Object>
浙公网安备 33010602011771号