ResultMap结果映射
ResultMap可以将查询结果映射为复杂类型的Java对象
ResultMap适用于java对象保存多表关联结果
ResultMap支持对象关联查询等高级操作
扩展出一个对象对查询结果进行保存
创建一个dto包src-main-java-com-MyBatis-dto
dto是一个特殊的JavaBean,JavaBean是一种Java类,符合一定编写规范,是一种实体与信息的规范。
JavaBean规范:
(1)必须有1个public 无参构造
(2)所有属性私有
(3)属性通过getter、setter方式暴露给其他程序
(4)类要求可序列化
在dto目录下创建GoodsDTO
package com.MyBatis.dto;
import com.MyBatis.entity.Goods;
public class GoodsDTO {
private Goods goods;
private String categoryName;
private String test;
public Goods getGoods() {
return goods;
}
public void setGoods(Goods goods) {
this.goods = goods;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
在Mapper XML中编写<select>标签并书写SQL语句
<!--结果映射-->
<resultMap id="rmGoods" type="com.MyBatis.dto.GoodsDTO">
<!--设置主键字段与属性映射-->
<id property="goods.goodsId" column="goods_id"></id>
<!--设置非主键字段与属性映射-->
<result property="goods.title" column="title"></result>
<result property="goods.currentPrice" column="current_price"></result>
<result property="goods.discount" column="discount"></result>
<result property="goods.isFreeDelivery" column="is_free_delivery"></result>
<result property="goods.categoryId" column="category_id"></result>
<result property="categoryName" column="category_name"></result>
<result property="test" column="test"></result>
</resultMap>
<select id="selectGoodsDTO" resultMap="rmGoods">
select g.*,c.category_name,'1' as test from t_goods g,t_category c
where g.category_id = c.category_id
</select>
测试
@Test
public void testSelectGoodsDTO(){
SqlSession sqlSession=null;
try{
sqlSession=MyBatisUtils.openSession();
List<GoodsDTO> list = sqlSession.selectList("goods.selectGoodsDTO");
for(GoodsDTO g : list){
System.out.println(g.getGoods().getTitle());
}
}catch (Exception e){
throw e;
}finally {
MyBatisUtils.closeSession(sqlSession);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!