持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第25天,点击查看活动详情
resultMap
select返回list集合
<select id="selectLikeName" resultType="com.caq.study.entity.Account">
select *
from account
where name like #{name}
</select>
List<Account> accounts = accountMapper.selectLikeName("%t%");
accounts.forEach(account-> System.out.println(account));
select封装map
不但可以将mybatis查询的结果封装为集合
也可以封装为map
通过@MapKey注解可以指定key值
@MapKey("name")
Map<String,Object> selectLikeNameMap(String name);
@MapKey("name")
Map<String,Account> selectLikeNameByMap(String name);
<select id="selectLikeNameByMap" resultType="map">
select *
from account
where name like #{name}
</select>
<select id="selectLikeNameMap" resultType="map">
select *
from account
where name like #{name}
</select>
自定义结果映射规则
对与复杂的查询,我们想让mybaits安装我们自定义的封装规则来封装。Mybatis提供了
<ResultMap>来自定义数据的封装规则。
指定主键列的封装规则id定义主键会底层有优化
column:指定哪一列
property:指定对应的javaBean属性
result定义普通列封装规则
如果不指定列的封装规则,则会按照默认规则进行封装
但只要我们写<ResultMap>一般把他们全写上
如下:
<resultMap id="MyEmp" type="com.caq.mybatis.bean.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="email" property="email"/>
</resultMap>
<select id="getEmpById" resultMap="MyEmp">
select * from tbl_employee where id = #{id};
</select>
级联属性封装结果
1、mapper接口
Account selectByResultMap(Integer id);
2、映射文件
<resultMap id="resultMapTest" type="com.caq.study.entity.Account">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<result column="money" property="money"></result>
<result column="id" property="dept.id"></result>
<result column="dept_name" property="dept.departName"></result>
</resultMap>
<select id="selectByResultMap" resultMap="resultMapTest">
SELECT
account.`id`,
account.`name`,
account.`money`,
depart.`id`,
depart.`dept_name`
FROM
`account`
LEFT JOIN `depart` ON account.d_id = depart.id
WHERE
account.id = #{id}
</select>
3、测试
@Test
public void testResultMap() throws IOException {
SqlSession sqlSession = getSqlSessionFactory().openSession();
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
Account account = accountMapper.selectByResultMap(1);
System.out.println(account);
sqlSession.commit();
sqlSession.close();
}
Account(id=1, name=tom, money=5000.00, dept=Dept(id=1, departName=开发部))
SQL
这个标签可以用来定义可重用的 SQL 代码片段,以便在其它语句中使用。
参数可以静态地(在加载的时候)确定下来,并且可以在不同的 include 元素中定义不同的参数值。
<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>
<select id="selectUsers" resultType="map">
select
<include refid="userColumns">
<property name="alias" value="t1"/>
</include>,
<include refid="userColumns">
<property name="alias" value="t2"/>
</include>
from some_table t1 cross join some_table t2
</select>
一般我们会把重复的sql字段提取出一个sql,然后不同的语句用这个sql字段的时候我们调这个提取出来的sql即可