mybatis(二):动态sql、关联查询

本文详细介绍了Mybatis中的动态SQL,包括If、Where和Foreach的使用,展示了如何处理多个ID的查询。此外,还探讨了Sql片段的提取和重用,以及如何进行一对一关联查询,分别通过resultType和resultMap两种方式实现。最后,讨论了Mybatis与Spring的整合,讲解了不同类型的Dao开发方式,强调了SqlSessionFactory在Spring容器中的重要性。
摘要由CSDN通过智能技术生成

输入映射和输出映射

​​​​​​parameterType(输入类型)

resultType(输出类型)

resultMap

resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。

如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。

<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.it.pojo.TbItemExample" >
	select
	<if test="distinct" >
	  distinct
	</if>
	<include refid="Base_Column_List" />
	from tb_item
	<if test="_parameter != null" >
	  <include refid="Example_Where_Clause" />
	</if>
	<if test="orderByClause != null" >
	  order by ${orderByClause}
	</if>
</select>
<resultMap id="BaseResultMap" type="com.it.pojo.TbItem" >
	<id column="id" property="id" jdbcType="BIGINT" />
	<result column="title" property="title" jdbcType="VARCHAR" />
	<result column="sell_point" property="sellPoint" jdbcType="VARCHAR" />
	<result column="price" property="price" jdbcType="BIGINT" />
	<result column="num" property="num" jdbcType="INTEGER" />
	<result column="barcode" property="barcode" jdbcType="VARCHAR" />
	<result column="image" property="image" jdbcType="VARCHAR" />
	<result column="cid" property="cid" jdbcType="BIGINT" />
	<result column="status" property="status" jdbcType="TINYINT" />
	<result column="created" property="created" jdbcType="TIMESTAMP" />
	<result column="updated" property="updated" jdbcType="TIMESTAMP" />
</resultMap>

动态sql

If & Where

<select id="findUserList" parameterType="user" resultType="user">
	select * from user 
	<where>
		<if test="id!=null and id!=''">
			and id=#{id}
		</if>
		<if test="username!=null and username!=''">
			and username like '%${username}%'
		</if>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值