|一、一对多查询
1、在sql中建立外键(user_Info和card_Info)
user_info:
card_info:
2、创建实体类
Userinfo类
CradInfo类
3、根据5个步骤
3.1 创建相同名称的xml和接口
3.2 在xml中编写查询的代码
<!--自定义sql -->
<resultMap type="com.createblue.bean.UserInfo" id="a">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="user_age" property="userAge"/>
<result column="user_sex" property="userSex"/>
<result column="card_id" property="cardId"/>
<!-- 一对一 -->
<association property="cardInfo" javaType="com.createblue.bean.CardInfo">
<id column="id" property="id"/>
<result column="card_num" property="cardNum"/>
<result column="address" property="address"/>
</association>
</resultMap>
<!--查询 -->
<select id="queryAll" parameterType="map"
resultMap="a">
select * from user_info t1 inner join card_info t2 on t1.card_id = t2.id
</select>
4、在UserInfomapper接口中调用
5、Controller
@Autowired
private UserInfoMapper ufm;
//查询所有
@RequestMapping("fun1")
public void queryAll(@RequestParam Map<String, Object> map) {
List<UserInfo> num = ufm.queryAll(map);
System.out.println(num);
}
| 二、一对多查询
1、实现思路,使用集合
<!-- 一对多 -->
<collection property="orderInfos" ofType="com.createblue.bean.OrderInfo">
<result column="order_name" property="orderName" />
<result column="order_no" property="orderNo" />
<result column="order_money" property="orderMoney" />
</collection>
查询语句
<select id="queryAll" resultMap="a" parameterType="map">
select * from user_info t1 inner join card_info t2 on t1.card_id = t2.id inner join order_info t3 on t1.id = t3.user_id
</select>
(ps:注意根据自己的表关系进行映射关系)
|三、多对多关系
<!--自定义sql -->
<resultMap type="com.createblue.bean.GoodInfo" id="good">
<id column="id" property="id"/>
<result column="good_name" property="goodName"/>
<result column="good_price" property="goodPrice"/>
<result column="good_desc" property="goodDesc"/>
<result column="card_id" property="cardId"/>
<!-- 多对多 -->
<collection property="orderInfos" ofType="com.createblue.bean.OrderInfo">
<result column="order_name" property="orderName" />
<result column="order_no" property="orderNo" />
<result column="order_money" property="orderMoney" />
</collection>
</resultMap>
<!--查询 -->
<select id="querygood" parameterType="map"
resultMap="good">
select * from good_info t1 inner join order_good t2 on t1.id = t2.good_id inner join order_info t3 on t3.id = t2.order_id
</select>
最后,进行调用
@Autowired
private GoodInfoMapper gm;
//多对多查询
@RequestMapping("fun2")
public void fun2(@RequestParam Map<String, Object> map) {
List<GoodInfo> num = gm.querygood(map);
System.out.println(num);
}
|–|--|
| | |