MyBatis中的表关联查询实现示例

网友投稿 484 2023-02-19

MyBatis中的表关联查询实现示例

MyBatis中的表关联查询实现示例

Mybatis中的一对多对象关联查询查询

模拟情景,商品与商品详情:一件商品可以对应多个商品详情信息,即从商品➡商品详情方向看,属于一对多。 在一对多关系中,需要在属于一的一方的实体类中添加多的一方的集合,一般为List<>类型

//(省去了get和set的方法)

public class Goods {

private Integer goodsId ;

private String title ;

private String subTitle ;

private Float originalCost ;

private Float currentPrice ;

private Float discount ;

private Integer isFreeDelivery ;

private Integer categoryId ;

//在一对多关系中,在一方添加多的一方的集合

private List goodsDetailLists ;

}

在"一方"实体类对应的xml 文件中,添加配置信息

column="goods_id">

column="goods_id">

select * from t_goods limit 0 , 1

在“多方”对应的xml文件中添加

resultTypwFTmgDTMPe="com.imooc.mybatis.entity.GoodsDetail">

select * from t_goods_detail where goods_id = #{value}

至此,关于商品到商品详情的一对多查询配置就完成了。

测试

//OneToMany

@Test

public void selectOneToMany(){

SqlSession sqlSession = null ;

try{

sqlSession = MybatisUtils.openSession() ;

List list = sqlSession.selectList("goods.selectOneToMany");

for (Goods g : list){

//输出商品和该商品的详情信息数量

System.out.println(g.getTitle() + ":" + g.getGoodsDetailLists().size());

}

}catch (Exception e){

e.printStackTrace();

wFTmgDTMP }finally {

MybatisUtils.closeSession(sqlSession);

}

}

Mybatis多对一对象关联查询

在上诉情景中,商品详情➡商品即为多对一的关系

在多对一关系中,需要在多的一方的实体类中添加一的一方的实体对象

public class GoodsDetail {

private Integer gdId ;

private Integer goodsId ;

private String gdPicUrl ;

private Integer gdOrder ;

//多对一:在多的一方添加一的一方的实体

private Goods goods ;

}

在多的一方xml文件中添加

http://

select * from t_goods_detail limit 0 , 1

测试

/**

* 多对一对象关联映射

* */

@Test

public void selectManyToOne(){

SqlSession sqlSession = null ;

try{

sqlSession = MybatisUtils.openSession() ;

List list = sqlSession.selectList("goodsDetail.selectManyToOne");

for (GoodsDetail gd : list){

System.out.println(gd.getGdPicUrl() + ":" + gd.getGoods().getTitle());

}

}catch (Exception e){

e.printStackTrace();

}finally {

MybatisUtils.closeSession(sqlSession);

}

}

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

上一篇:移动应用开发模式(移动应用开发什么意思)
下一篇:开发小程序用vue(开发小程序用什么框架)
相关文章

 发表评论

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