一、关联映射
1:一对一
1)在需要关联的实体对象中引用另外一个对象
2)在xml中的的<resultMap>引用进来:
<association property="card" column="card_id" select="xx.xx.xx.CardMapper.selectCardById" javaType="xx.xx.xx.Card"/>
select属性表示会使用column属性的card_id值作为参数执行CardMapper中定义的selectCardById
查询对应的Card数据,查询出的数据被封装到引用的对象中。
2:一对多
1)在需要关联的实体对象中引用另外的对象封装成List,例如:
private List<Student> students; get、set方法
2)在xml中的的<resultMap>引用进来:
<collection property="students" javaType="ArrayList"column="id" ofType="xx.xx.xx.Student"
select="xx.xx.mapper.StudentMapper.selectStudentByClazzId" fechType="lazy">
这里加载需要的字段
</collection>
fetchType有两个值 eager、lazy 表示立即加载和懒加载。
3)需要在mybatis-config.xml中增加如下配置:
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
setting name="aggressiveLazyLoading" value="false"/>
</settings>
lazyLoadingEnabled:表示延迟加载的全局开关,当开启时所有关联对象都会延迟加载。默认false。
aggressiveLazyLoading:启用时,会使带有延迟加载属性的对象立即加载;反之,每种属性将会按需加载。默认true。
3:多对一
跟一对多差不多
<collection property="students" javaType="xx.xx.xx.Student">
这里加载需要的字段
</collection>
4:多对多
1)在需要关联的实体对象中引用另外一个对象,例如:private List<Student> students; get、set方法
2)在xml中的的<resultMap>引用进来:
<collection property="articles" javaType="ArrayList" column="oid" oftype="xx.xx.xx.Article"
select="xx.xx.mapper.ArticleMapper.selectArticleByOrderId" fetchType="lazy">
这里配置需要加载的字段
</collection>
<!--如果查询出来的列同名,则需要使用别名来区分,在resultMap 里面更改别名-->
3)一般多对多查询需要借助中间表来关联
二、动态SQL
1:if
<if test="name != null and name != ''" >
</if>
2:choose
<choose>
<when test="id != null"></when>
<when test="variety_id!=1"></when>
<otherwise>
and id=1
</otherwise>
</choose>
表示: if else if else
在<if>标签外面加用于判断语句
可以被用于动态包含需要更新的列,而舍去其他的。
<set>
<if test="userId != null">
user_id = #{userId,jdbcType=BIGINT},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
</set>
5:foreach
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
6:bind
表示创建一个变量然后绑定到上下文中
<select id="findAnalystPageList" resultType="com.bob.analyst.vo.AnalystVO" parameterType="com.bob.analyst.vo.AnalystVO">
<bind name="name" value="'%'+_parameter.getName()+'%'"/>
select
<include refid="Base_Column_List" />
from tbl_analyst
where is_delete=0
<if test="name != null and name != ''" >
and name like #{name}
</if>
ORDER BY create_time desc
</select>