Mybatis 各种标签使用

本文介绍了如何在Spring Boot项目中使用MyBatis进行用户与分数关联查询,展示了 resultMap、resultType、foreach、if、include和一对多关联映射的实践。重点讲解了如何通过SQL和数据映射实现动态查询和复杂关系数据获取。
	@Data
	public class User{
	    private Long id;
	    private String name;
	}
	@Data
	public class Score{
	    private Long id;
	    private Integer score;
	    private Long subjectId;
	    private Long userId;
	}
	
	<resultMap id="userResult"    type="User">   </resultMap>
    <resultMap type="User" id="userExt">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
		<collection property="scoreList" column="user_id" javaType="List" ofType="Score"  >
			<result property="userId" column="user_id"/>
			<result property="score" column="score"/>
			<result property="subjectId" column="subject_id"/>
		</collection >
	</resultMap>
	
	<sql id="commonUserColumns">id,name</sql>
	
	// resultMap
    <select id="findUserById" resultMap="userResult">
        select age,name  from t_user user  where  user.id = #{userId}
    </select>
 
    // resultType
    <select id="findUserById" resultType="User">
        select age,name  from t_user user  where  user.id = #{userId}
    </select>
   
    // foreach
	<select id="findUserByUserList" resultType="User">
        select age,name  from t_user user  where  user.id in 
 			<foreach item="user" index="index" collection="userList" open="(" separator="," close=")">
					#{user.id}
 			</foreach>
    </select>
    
    // if
    <select id="findUserByName" resultType="User">
        select age,name  from t_user user 
        <if test="null != userName and userName != ""  ">
			where user.name = #{userName}
		</if>
    </select>
  
   // include 
   <select id="findUserByName" resultType="User">
        select  <include refid="commonUserColumns" />
        from t_user user 
    </select>
   
   // 一对多 
   <select id="findUserByName" resultMap="userExt">
        select  id,name,socre,subject_id
        from t_user user left join t_score score on user.id = score.user_id 
    </select>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值