XML 映射文件 insert, update 和 delete 1 2 3 4 5 6 7 8 9 10 public interface EmployeeMapper { public Employee getEmpById (Integer id) ; public void addEmp (Employee employee) ; public void updateEmp (Employee employee) ; public void deleteEmpById (Integer id) ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <insert id ="addEmp" parameterType ="com.company.mybatis.bean.Employee" useGeneratedKeys ="true" keyProperty ="id" > insert into tbl_employee(last_name,email,gender) values(#{lastName},#{email},#{gender})</insert > <update id ="updateEmp" > update tbl_employee set last_name=#{lastName},email=#{email},gender=#{gender} where id=#{id}</update > <delete id ="deleteEmpById" > delete from tbl_employee where id=#{id}</delete >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 @Test public void test03 () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(true ); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); Employee employee = new Employee (null , "jerry" , "jerry@123.com" , "1" ); mapper.addEmp(employee); System.out.println(employee.getId()); }finally { openSession.close(); } }
类型返回值与手动提交数据 mybatis允许增删改直接定义以下类型返回值Integer、Long、Boolean、void 我们需要手动提交数据sqlSessionFactory.openSession();===》手动提交 sqlSessionFactory.openSession(true);===》自动提交
insert-获取自增主键的值 parameterType:参数类型,可以省略 获取自增主键的值:mysql支持自增主键,自增主键值的获取,mybatis也是利用statement.getGenreatedKeys(); useGeneratedKeys=“true”
;使用自增主键获取主键值策略keyProperty
;指定对应的主键属性,也就是mybatis获取到主键值以后,将这个值封装给javaBean的哪个属性 1 2 3 4 5 <insert id ="addEmp" parameterType ="com.company.mybatis.bean.Employee" useGeneratedKeys ="true" keyProperty ="id" > insert into tbl_employee(last_name,email,gender) values(#{lastName},#{email},#{gender}) </insert >
官方文档:insert、update、delete
insert-Oracle使用序列生成主键演示 Oracle不支持自增;Oracle使用序列来模拟自增; 每次插入的数据的主键是从序列中拿到的值;如何获取到这个值; 1 2 #从序列获取新主键值select employee_seq.nextval from dual;
insert-获取非自增主键的值-selectKey 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <insert id ="addEmp" databaseId ="oracle" > <selectKey keyProperty ="id" order ="BEFORE" resultType ="Integer" > select EMPLOYEES_SEQ.nextval from dual </selectKey > insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL) values(#{id},#{lastName},#{email}) </insert >
selectKey 元素的属性
keyProperty selectKey 语句结果应该被设置到的目标属性。如果生成列不止一个,可以用逗号分隔多个属性名称。 keyColumn 返回结果集中生成列属性的列名。如果生成列不止一个,可以用逗号分隔多个属性名称。 resultType 结果的类型。通常 MyBatis 可以推断出来,但是为了更加准确,写上也不会有什么问题。MyBatis 允许将任何简单类型用作主键的类型,包括字符串。如果生成列不止一个,则可以使用包含期望属性的 Object 或 Map。 order 可以设置为 BEFORE 或 AFTER。如果设置为 BEFORE,那么它首先会生成主键,设置 keyProperty 再执行插入语句。如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 中的语句 - 这和 Oracle 数据库的行为相似,在插入语句内部可能有嵌入索引调用。 statementType 和前面一样,MyBatis 支持 STATEMENT,PREPARED 和 CALLABLE 类型的映射语句,分别代表 Statement, PreparedStatement 和 CallableStatement 类型。
参数处理 单个参数&多个参数&命名参数 单个参数:mybatis不会做特殊处理, 多个参数:mybatis会做特殊处理。通常操作方法:public Employee getEmpByIdAndLastName(Integer id,String lastName); 取值:#{id}
,#{lastName}
上述操作会抛出异常:org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [1, 0, param1, param2]
多个参数会被封装成 一个map,key:param1…paramN,或者参数的索引也可以 value:传入的参数值 #{}
就是从map中获取指定的key的值; 【命名参数】:明确指定封装参数时map的key;@Param(“id”)
多个参数会被封装成 一个map,key:使用@Param注解指定的值 value:参数值 #{指定的key}
取出对应的参数值 1 2 3 4 5 6 public interface EmployeeMapper { public Employee getEmpByIdAndLastName (@Param("id") Integer id, @Param("lastName") String lastName) ; public Employee getEmpByIdAndLastName02 (Integer id,String lastName) ; }
1 2 3 4 5 6 7 8 9 10 11 12 <select id ="getEmpById" resultType ="com.company.mybatis.bean.Employee" databaseId ="mysql" > select id,last_name lastName,gender,email from tbl_employee where id=#{id}</select > <select id ="getEmpByIdAndLastName" resultType ="com.company.mybatis.bean.Employee" > select * from tbl_employee where id=#{id} and last_Name=#{lastName}</select > <select id ="getEmpByIdAndLastName02" resultType ="com.company.mybatis.bean.Employee" > select * from tbl_employee where id=#{0} and last_Name=#{1}</select >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 @Test public void test04Parameters () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(true ); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); System.out.println(mapper.getEmpByIdAndLastName02(1 ,"tom" )); System.out.println(mapper.getEmpByIdAndLastName(1 , "tom" )); } finally { openSession.close(); } }
POJO&Map&TO POJO:如果多个参数正好是我们业务逻辑的数据模型,我们就可以直接传入pojo; Map:如果多个参数不是业务模型中的数据,没有对应的pojo,不经常使用,为了方便,我们也可以传入map 如果多个参数不是业务模型中的数据,但是经常要使用,推荐来编写一个TO(Transfer Object)数据传输对象,如: 1 2 3 4 Page{ int index; int size; }
1 2 3 4 public interface EmployeeMapper { public Employee getEmpByMap (Map<String,Object> map) ; }
1 2 3 4 <select id ="getEmpByMap" resultType ="com.company.mybatis.bean.Employee" > select * from employee where id = #{id} and last_name=#{lastName} </select >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 @Test public void test04Parameters () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(true ); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); HashMap<String, Object> map = new HashMap <>(); map.put("id" ,1 ); map.put("lastName" ,"Tom" ); Employee empByMap = mapper.getEmpByMap(map); System.out.println(empByMap); } finally { openSession.close(); } }
参数封装扩展思考(如何获取参数) 思考========
public Employee getEmp(@Param("id")Integer id,String lastName);
取值:id==>#{id/param1} lastName==>#{param2} public Employee getEmp(Integer id,@Param("e")Employee emp);
取值:id==>#{param1} lastName===>#{param2.lastName/e.lastName} 特别注意 :如果是Collection(List、Set)类型或者是数组,也会特殊处理。也是把传入的list或者数组封装在map中 key:Collection(collection),如果是List还可以使用这个key(list) public Employee getEmpById(List<Integer> ids);
源码分析-参数封装map的过程 结合源码,mybatis怎么处理参数
(@Param(“id”)Integer id,@Param(“lastName”)String lastName);
ParamNameResolver
解析参数封装map的;names:{0=id, 1=lastName};构造器的时候就确定好了 确定流程:
获取每个标了param注解的参数的@Param的值:id,lastName; 赋值给name;
每次解析一个参数给map中保存信息:(key:参数索引,value:name的值)
name的值:
标注了param注解:注解的值
没有标注:
全局配置:useActualParamName(jdk1.8):name=参数名 name=map.size();相当于当前元素的索引{0=id, 1=lastName,2=2} args【1,“Tom”,‘hello’】:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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()]); final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1 ); if (!names.containsValue(genericParamName)) { param.put(genericParamName, args[entry.getKey()]); } i++; } return param; } } }
总结 :参数多时会封装map,为了不混乱,我们可以使用@Param来指定封装时使用的key;#{key}就可以取出map中的值;
#与$取值区别 #{}
和${}
都可以获取map中的值或者pojo对象属性的值;
1 2 3 select * from tbl_employee where id= ${id} and last_name= #{lastName} #Preparing:select * from tbl_employee where id= 2 and last_name= ?
区别 :
#{}
: 是以预编译的形式,占位符,将参数设置到sql语句中;PreparedStatement;防止sql注入${}
: 取出的值直接拼装 在sql语句中;会有安全问题;大多情况下,我们去参数的值都应该去使用#{}
。
原生jdbc不支持占位符的地方我们就可以使用${}
进行取值,比如分表、排序。。。;按照年份分表拆分
1 2 select * from ${year }_salary where xxx;select * from tbl_employee order by ${f_name} ${order }
#取值时指定参数相关规则 #{}
:更丰富的用法:
规定参数的一些规则:
javaType jdbcType mode(存储过程) numericScale resultMap typeHandler jdbcTypeName expression(未来准备支持的功能) 例如:jdbcType
jdbcType通常需要在某种特定的条件下被设置:
在我们数据为null的时候,有些数据库可能不能识别mybatis对null的默认处理。比如Oracle DB(报错); JdbcType OTHER:无效的类型;因为mybatis对所有的null都映射的是原生Jdbc的OTHER类型,Oracle DB不能正确处理; 由于全局配置中:jdbcTypeForNull=OTHER,Oracle DB不支持,两种解决方法:
在mapper文件中写#{email,jdbcType=NULL}
; 在全局配置文件<setting name="jdbcTypeForNull" value="NULL"/>
Select 返回List EmployeeMapper.java
1 2 3 public interface EmployeeMapper { public List<Employee> getEmpsByLastNameLike (String LastName) ; }
EmployeeMapper.xml
1 2 3 4 5 <select id ="getEmpsByLastNameLike" resultType ="Employee" > Select * from tbl_employee where last_name like #{lastName}</select >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Test public void testList () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(true ); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); List<Employee> empsByLastNameLike = mapper.getEmpsByLastNameLike("%e%" ); for (Employee employee : empsByLastNameLike) { System.out.println(employee); } }finally { openSession.close(); } }
记录封装map EmployeeMapper.java
1 2 3 4 5 6 7 8 9 10 public interface EmployeeMapper { @MapKey("id") public Map<Integer,Employee> getEmpByLastNameLikeReturnMap (String lastName) ; public Map<String,Object> getEmpByIdReturnMap (Integer id) ; }
EmployeeMapper.xml
1 2 3 4 5 6 7 8 9 <select id ="getEmpByLastNameLikeReturnMap" resultType ="com.company.mybatis.bean.Employee" > select * from tbl_employee where last_name like #{lastName} </select > <select id ="getEmpByIdReturnMap" resultType ="map" > select * from tbl_employee where id=#{id} </select >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @Test public void testMap () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); Map<String, Object> empByIdReturnMap = mapper.getEmpByIdReturnMap(1 ); System.out.println(empByIdReturnMap); openSession.commit(); Map<Integer, Employee> empByLastNameLikeReturnMap = mapper.getEmpByLastNameLikeReturnMap("%r%" ); System.out.println(empByLastNameLikeReturnMap); }finally { openSession.close(); } }
resultMap 自定义结果映射规则 EmployeeMapperPlus.java
1 2 3 4 public interface EmployeeMapperPlus { public Employee getEmpById (Integer id) ; }
EmployeeMapperPlus.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?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.company.mybatis.dao.EmployeeMapperPlus" > <resultMap type ="com.company.mybatis.bean.Employee" id ="MyEmp" > <id column ="id" property ="id" > </id > <result column ="last_name" property ="lastName" /> </resultMap > <select id ="getEmpById" resultMap ="MyEmp" > select * from tbl_employee where id=#{id} </select > </mapper >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void testResultMap () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class); Employee empById = mapper.getEmpById(1 ); System.out.println(empById); }finally { openSession.close(); } }
关联查询-环境搭建 创建数据库表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 CREATE TABLE tbl_dept( id INT (11 ) PRIMARY KEY AUTO_INCREMENT, dept_name VARCHAR (255 ) )INSERT INTO tbl_dept(dept_name) VALUES ('开发部' ) INSERT INTO tbl_dept(dept_name) VALUES ('测试部' ) SELECT * FROM tbl_dept ALTER TABLE tbl_employee ADD COLUMN d_id INT (11 );ALTER TABLE tbl_employee ADD CONSTRAINT fk_emp_deptFOREIGN KEY(d_id) REFERENCES tbl_dept(id)
新建类Department.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public class Department { private Integer id; private String departmentName; public Department (Integer id, String departmentName) { this .id = id; this .departmentName = departmentName; } public Department () { } public Integer getId () { return id; } public void setId (Integer id) { this .id = id; } public String getDepartmentName () { return departmentName; } public void setDepartmentName (String departmentName) { this .departmentName = departmentName; } @Override public String toString () { return "Department{" + "id=" + id + ", departmentName='" + departmentName + '\'' + '}' ; } }
关联查询-级联属性封装结果 EmployeeMapperPlus.java
1 2 3 4 public interface EmployeeMapperPlus { public Employee getEmpAndDept (Integer id) ; }
EmployeeMapperPlus.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <resultMap id ="MyDifEmp" type ="com.company.mybatis.bean.Employee" > <id column ="tbl_employee.id" property ="id" /> <result column ="last_name" property ="lastName" /> <result column ="gender" property ="gender" /> <result column ="d_id" property ="dept.id" /> <result column ="dept_name" property ="dept.departmentName" /> </resultMap > <select id ="getEmpAndDept" resultMap ="MyDifEmp" > SELECT tbl_employee.id,last_name,gender,tbl_employee.d_id,dept_name FROM tbl_employee LEFT JOIN tbl_dept ON tbl_employee.id=tbl_dept.id WHERE tbl_employee.id=tbl_dept.id AND tbl_employee.id=#{id}</select >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void testResultMapAssociation () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class); Employee empAndDept = mapper.getEmpAndDept(1 ); System.out.println(empAndDept); System.out.println(empAndDept.getDept()); }finally { } }
关联查询-association定义关联对象封装规则 EmployeeMapperPlus.java
1 2 3 4 public interface EmployeeMapperPlus { public Employee getEmpAndDept2 (Integer id) ;
EmployeeMapperPlus.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 </resultMap > <resultMap id ="MyDifEmp2" type ="com.company.mybatis.bean.Employee" > <id column ="tbl_employee.id" property ="id" /> <result column ="last_name" property ="lastName" /> <result column ="gender" property ="gender" /> <association property ="dept" javaType ="com.company.mybatis.bean.Department" > <id column ="d_id" property ="id" /> <result column ="dept_name" property ="departmentName" > </result > </association > <select id ="getEmpAndDept2" resultMap ="MyDifEmp2" > SELECT tbl_employee.id,last_name,gender,tbl_employee.d_id,dept_name FROM tbl_employee LEFT JOIN tbl_dept ON tbl_employee.id=tbl_dept.id WHERE tbl_employee.id=tbl_dept.id AND tbl_employee.id=#{id}</select >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void testResultMapAssociation02 () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class); Employee empAndDept = mapper.getEmpAndDept2(1 ); System.out.println(empAndDept); System.out.println(empAndDept.getDept()); }finally { openSession.close(); } }
关联查询-association分步查询 DepartmentMapper.java
1 2 3 4 public interface DepartmentMapper { public Department getDeptById (Integer id) ; }
EmployeeMapperPlus.java
1 2 3 4 public interface EmployeeMapperPlus { public Employee getEmpByIdStep (Integer id) ; }
DepartmentMapper.xml
1 2 3 4 5 6 7 8 9 10 11 <?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.company.mybatis.dao.DepartmentMapper" > <select id ="getDeptById" resultType ="com.company.mybatis.bean.Department" > select id,dept_name departmentName from tbl_dept where id=#{id} </select > </mapper >
EmployeeMapperPlus.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <resultMap id ="MyEmpByStep" type ="com.company.mybatis.bean.Employee" > <id column ="id" property ="id" /> <result column ="last_name" property ="lastName" > </result > <result column ="email" property ="email" > </result > <result column ="gender" property ="gender" > </result > <association property ="dept" select ="com.company.mybatis.dao.DepartmentMapper.getDeptById" column ="d_id" > </association > </resultMap > <select id ="getEmpByIdStep" resultMap ="MyEmpByStep" > select * from tbl_employee where id=#{id} </select >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 @Test public void testResultMapAssociation03 () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class); Employee empByIdStep = mapper.getEmpByIdStep(1 ); System.out.println(empByIdStep); }finally { openSession.close(); } }
关联查询-分步查询&延迟加载 我们每次查询Employee对象的时候,都将一起查询出来。部门信息在我们使用的时候再去查询;分段查询的基础之上加上两个配置:
在全局配置文件中配置,实现懒加载
mybatis-config.xml
1 2 3 4 5 6 7 8 9 <configuration > ... <settings > ... <setting name ="lazyLoadingEnabled" value ="true" /> <setting name ="aggressiveLazyLoading" value ="false" /> </settings >
lazyLoadingEnabled 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType
属性来覆盖该项的开关状态。 true|false false aggressiveLazyLoading 开启时,任一方法的调用都会加载该对象的所有延迟加载属性。 否则,每个延迟加载属性会按需加载(参考 lazyLoadTriggerMethods
)。 true|false false在 3.4.1 及之前的版本中默认为 true)
关联查询-collection定义关联集合封装规则 DepartmentMapper.java
1 2 3 4 public interface DepartmentMapper { public Department getDeptByIdPlus (Integer id) ; }
DepartmentMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 <mapper namespace ="com.company.mybatis.dao.DepartmentMapper" > <resultMap id ="MyDept" type ="com.company.mybatis.bean.Department" > <id column ="did" property ="id" /> <result column ="dept_name" property ="departmentName" /> <collection property ="emps" ofType ="com.company.mybatis.bean.Employee" > <id column ="eid" property ="id" /> <result column ="last_name" property ="lastName" /> <result column ="email" property ="email" /> <result column ="gender" property ="gender" /> </collection > </resultMap > <select id ="getDeptByIdPlus" resultMap ="MyDept" > SELECT d.id AS did ,d.dept_name AS dept_name, e.id AS eid,e.last_name AS last_name, e.email AS email,e.gender AS gender FROM tbl_dept AS d LEFT JOIN tbl_employee AS e ON d.id=e.d_id WHERE d.id=#{id} </select >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Test public void testGetDeptByIdPlus () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(true ); try { DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class); Department department = mapper.getDeptByIdPlus(1 ); System.out.println(department); System.out.println(department.getEmps()); }finally { openSession.close(); } }
关联查询-collection分步查询&延迟加载 DepartmentMapper.java
1 2 3 4 5 public interface DepartmentMapper { public List<Employee> getEmpsByDeptId (Integer deptId) ; public Department getDeptByIdStep (Integer id) ; }
EmployeeMapper.xml
1 2 3 4 <select id ="getEmpsByDeptId" resultType ="com.company.mybatis.bean.Employee" > select * from tbl_employee where d_id=#{deptId} </select >
DepartmentMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 <resultMap id ="MyDeptStep" type ="com.company.mybatis.bean.Department" > <id column ="id" property ="id" /> <id column ="dept_name" property ="departmentName" /> <collection property ="emps" select ="com.company.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId" column ="id" > </collection > </resultMap > <select id ="getDeptByIdStep" resultMap ="MyDeptStep" > select id,dept_name departmentName from tbl_dept where id=#{id} </select >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Test public void testGetDeptByIdStep () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(true ); try { DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class); Department deptByIdStep = mapper.getDeptByIdStep(1 ); System.out.println(deptByIdStep); System.out.println(deptByIdStep.getEmps()); }finally { openSession.close(); } }
分步查询传递多列值&fetchType 扩展:
多列的值传递过去:将多列的值封装map传递;column="{key1=column1,key2=column2}"
fetchType=“lazy”:表示使用延迟加载; DepartmentMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 <resultMap id ="MyDeptStep" type ="com.company.mybatis.bean.Department" > <id column ="id" property ="id" /> <id column ="dept_name" property ="departmentName" /> <collection property ="emps" select ="com.company.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId" column ="{deptId=id}" fetchType ="lazy" > </collection > </resultMap > <select id ="getDeptByIdStep" resultMap ="MyDeptStep" > select id,dept_name departmentName from tbl_dept where id=#{id} </select >
discriminator鉴别器 EmployeeMapperPlus.java
1 2 3 4 5 public interface EmployeeMapperPlus { public List<Employee> getEmpsWithDiscriminator () ; }
EmployeeMapperPlus.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <resultMap id ="MyEmpDis" type ="com.company.mybatis.bean.Employee" > <id column ="id" property ="id" /> <result column ="last_name" property ="lastName" > </result > <result column ="email" property ="email" > </result > <result column ="gender" property ="gender" > </result > <discriminator javaType ="string" column ="gender" > <case value ="0" resultType ="com.company.mybatis.bean.Employee" > <association property ="dept" select ="com.company.mybatis.dao.DepartmentMapper.getDeptById" column ="d_id" fetchType ="eager" > </association > </case > <case value ="1" resultType ="com.company.mybatis.bean.Employee" > <id column ="id" property ="id" /> <result column ="last_name" property ="lastName" > </result > <result column ="last_name" property ="email" > </result > <result column ="gender" property ="gender" > </result > </case > </discriminator > </resultMap > <select id ="getEmpsWithDiscriminator" resultMap ="MyEmpDis" > select * from tbl_employee limit 10</select >
EmployeeMapperTest.java
1 2 3 4 5 6 7 8 9 10 11 @Test public void testGetEmpsWithDiscriminator () throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class); System.out.println(mapper.getEmpsWithDiscriminator()); } finally { openSession.close(); } }