Mybatis select记录封装的实现

网友投稿 242 2022-11-16


Mybatis select记录封装的实现

select记录封装

返回一个List集合, resultType要写集合中元素的类型

select * from tbl_employee where last_name like #{lastName}

返回一条记录的map, key为列名, 值就是对应的值

select * from tbl_employee where id=#{id}

多条记录封装成一个map, key为id, 值是记录封装后的javaBean

//@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key

@MapKey("lastName")

public Map getEmpByLastNameLikeReturnMap(String lastName);

select * from tbl_employee where last_name like #{lastName}

自动映射配置

全局setting设置

1.autoMappingBehavior默认为PARTIAL, 开启自动映射功能;唯一的要求是列名和javaBean属性名一致

2.mapUnderscoreToCamelCase=true, 开启自动驼峰命名规范映射功能

自定义resultMap, 实现高级映射功能

resultMap自定义映射规则

创建表

create table tb_dept (

id int(11) primary key auto_increment,

dept_name varchar(255)

)

添加列

alter table tb_emp add column d_id int(11);

添加约束

alter table tb_emp add constraint fk_emp_dept foreign key(d_id) references tb_dept(id);

联合查询:级联属性封装结果集

场景一:

查询Employee的同时查询员工对应的部门;一个员工有与之对应的部门信息;

使用association定义关联的单个对象的封装规则;

association分步查询

select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"

column="d_id">

select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"

column="d_id">

select id,dept_name departmentName from tbl_dept where id=#{id}

association分步查询&延迟加载

关联集合

嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则

场景二:

查询部门的时候将部门对应的所有员工信息也查询出来:注释在DepartmentMapper.xml中

SELECT d.id did,d.dept_name dept_name,

e.id eid,e.last_name last_name,e.email email,e.gender gender

FROM tbl_dept d

LEFT JOIN tbl_employee e

ON d.id=e.d_id

WHERE d.id=#{id}

collection:分段查询

select="com.atguigu.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"

column="{deptId=id}" fetchType="lazy">

select="com.atguigu.mybatis.dao.EmployeeMapperPlus.getEmpsByDeptId"

column="{deptId=id}" fetchType="lazy">

select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"

column="d_id">

select="com.atguigu.mybatis.dao.DepartmentMapper.getDeptById"

column="d_id">


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java 生成随机验证码图片的示例
下一篇:Java ByteBuffer网络编程用法实例解析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~