單表查詢
單表查詢在《初始Mybatis》中已經介紹過,這里就不在介紹了。咱們這里只說單表查詢中的“like查詢”。
like查詢單獨使用#{}報錯
<select id="selectByKeyword" resultType="com.example.demo.entity.Userinfo">select * from userinfo where username like '%#{username}%'
</select>
轉換成jdbc代碼如下
正確的打開方式是配合concat函數使用
<select id="selectByKeyword" resultType="com.example.demo.entity.Userinfo">select * from userinfo where username like concat('%', #{username}, '%')
</select>
此時的轉換成jdbc代碼如下:
多表聯查
resultType和resultMap
在咱們前面幾篇文章中,在select標簽中返回類型都是使用resultType,這是因為resultType使用簡單,所以大部分查詢場景都是使用resultType。
而resultMap用來返回字典映射,resultMap使用場景如下:
- 數據庫中的字段名和程序中的屬性名不同時,可使用resultMap 配置映射
- 在一對一和一對多中使用resultMap映射并查詢數據
字段名和屬性名不同的情況,使用resultMap解決
程序的屬性:
通過id查詢用戶信息
<select id="selectById" resultType="com.example.demo.entity.Userinfo">select * from userinfo where id = #{id}
</select>
單元測試代碼:
@Test
void selectById() {int id = 1;Userinfo userinfo = userMapper.selectById(id);System.out.println("用戶名:" + userinfo.getName());
}
mybatis是ORM框架,將mysql查詢結果放到程序實體類中,當數據庫的字段名和屬性名相同時就會賦值,由于在數據庫中是username,而實體類中是name,無法對應起來,導致賦值失敗。
此時可以通過resultMap解決
<resultMap id="baseMap" type="com.example.demo.entity.Userinfo"><id column="id" property="id"></id><result column="username" property="name"></result><result column="password" property="password"></result><result column="photo" property="photo"></result><result column="createtime" property="createtime"></result><result column="updatetime" property="updatetime"></result><result column="state" property="state"></result>
</resultMap><select id="selectById" resultMap="baseMap">select * from userinfo where id = #{id}
</select>
此時再運行單元測試代碼:
使用as別名解決
<select id="selectById2" resultType="com.example.demo.entity.Userinfo">select username as name, password, photo, createtime, updatetime, state from userinfo where id
</select>
多表查詢
現在除了userinfo表,還有一個文章表articleinfo.
需求:在文章表中根據文章id查詢文章作者和文章信息
在文章表中并沒有username字段,所以需要將articleinfo表和userinfo表聯查(因為要展示文章信息所以是left join),聯查的條件是articleinfo.uid = userinfo.id.得到的結果既不是userinfo也不是articleinfo,所以我們需要繼承articleinfo,創建一個articleinfoVO對象。(VO就是View Object視圖對象)
@Mapper
public interface ArticleMapper {public ArticleinfoVO getById(@Param("id") Integer id);
}
<?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.example.demo.mapper.ArticleMapper"><select id="getById" resultType="com.example.demo.entity.vo.ArticleinfoVO">select articleinfo.* , userinfo.username from articleinfo left join userinfoon userinfo.id = articleinfo.uidwhere articleinfo.id = #{id}</select>
</mapper>
@SpringBootTest
@Transactional
class ArticleMapperTest {@Autowiredprivate ArticleMapper articleMapper;@Testvoid getById() {ArticleinfoVO articleinfoVO = articleMapper.getById(1);System.out.println(articleinfoVO.toString());}
}
總結:多表查詢時使用連表查詢(left join/inner join) + XXXVO解決