vs网站开发,杭州旅游团购网站建设,wordpress安卓版5,网络推广方式主要有单表查询
单表查询在《初始Mybatis》中已经介绍过#xff0c;这里就不在介绍了。咱们这里只说单表查询中的“like查询”。like查询单独使用#{}报错
select idselectByKeyword resultTypecom.example.demo.entity.Userinfoselect * from use…
单表查询
单表查询在《初始Mybatis》中已经介绍过这里就不在介绍了。咱们这里只说单表查询中的“like查询”。like查询单独使用#{}报错
select idselectByKeyword resultTypecom.example.demo.entity.Userinfoselect * from userinfo where username like %#{username}%
/select转换成jdbc代码如下正确的打开方式是配合concat函数使用
select idselectByKeyword resultTypecom.example.demo.entity.Userinfoselect * from userinfo where username like concat(%, #{username}, %)
/select此时的转换成jdbc代码如下
多表联查 resultType和resultMap
在咱们前面几篇文章中在select标签中返回类型都是使用resultType,这是因为resultType使用简单所以大部分查询场景都是使用resultType。而resultMap用来返回字典映射resultMap使用场景如下
数据库中的字段名和程序中的属性名不同时可使用resultMap 配置映射在一对一和一对多中使用resultMap映射并查询数据
字段名和属性名不同的情况使用resultMap解决
程序的属性通过id查询用户信息
select idselectById resultTypecom.example.demo.entity.Userinfoselect * 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 idbaseMap typecom.example.demo.entity.Userinfoid columnid propertyid/idresult columnusername propertyname/resultresult columnpassword propertypassword/resultresult columnphoto propertyphoto/resultresult columncreatetime propertycreatetime/resultresult columnupdatetime propertyupdatetime/resultresult columnstate propertystate/result
/resultMapselect idselectById resultMapbaseMapselect * from userinfo where id #{id}
/select此时再运行单元测试代码
使用as别名解决
select idselectById2 resultTypecom.example.demo.entity.Userinfoselect 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 version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.example.demo.mapper.ArticleMapperselect idgetById resultTypecom.example.demo.entity.vo.ArticleinfoVOselect articleinfo.* , userinfo.username from articleinfo left join userinfoon userinfo.id articleinfo.uidwhere articleinfo.id #{id}/select
/mapperSpringBootTest
Transactional
class ArticleMapperTest {Autowiredprivate ArticleMapper articleMapper;Testvoid getById() {ArticleinfoVO articleinfoVO articleMapper.getById(1);System.out.println(articleinfoVO.toString());}
}总结多表查询时使用连表查询left join/inner join) XXXVO解决