在hibernate学习中,实体映射关系配置一直都让人比较头疼;一对多、多对一、创建主外键,多的一端负责维护管理外键关系 。。Balabala。。。另外面向对象进行操作的hql语句,当涉及多表主外键关联查询时,hql的书写也是让人比较头疼的。
Mybatis在这两点上都有自己独到的处理方式,下面以【先实例,后总结】的方式为大家逐一道来。
一、1:N实体关系配置
1、实体关系
一个command指令ID对应多条content实体
- public class Command {
- private int Id;
- private String name;
- private String description;
- private List<Content> content;
- }
- public class Content {
- private int Id;
- private String commandID;
- private String content;
- }
2、实体关系配置
- <mapper namespace="Command">
- <resultMap type="cn.max.domain.Command" id="Command">
- <id column="Id" jdbcType="INTEGER" property="id"/>
- <result column="name" jdbcType="VARCHAR" property="name"/>
- <result column="description" jdbcType="VARCHAR" property="description"/>
- <collection property="content" resultMap="Command"/> <!-通过<span style="font-family: SimSun;">collection标签表示command中content实体集合属性</span><span style="font-family: SimSun;">-></span>
- </resultMap>
- <mapper namespace="Content">
- <!-- TYPE message类路径 -->
- <resultMap type="cn.max.domain.Content" id="MsgResult">
- <id column="Id" jdbcType="INTEGER" property="id"/>
- <result column="commandId" jdbcType="VARCHAR" property="commandId"/>
- <result column="content" jdbcType="VARCHAR" property="content"/>
- </resultMap>
- </mapper>
根据两个实体1:N的实体关系,command实体中自然加入一个List或者set类型content集合。对应command配置文件中,使用[collection]标签配置属性为content即可。
这样根据实体所有属性进行xml文件配置,并且就一[collection]标签即可表示两者间1:n的关联关系,对比于hibernate各种丰富的尸体关联关系标签,显得简洁明了许多。
二、动态SQL拼接实现表关联查询
通过上述步骤便配置好了command和content实体的对应关系,接下来就是在command.xml中使用sql标签,通过command的name属性关联查询出对应content集合了。
- <select id="queryCommandList" parameterType="cn.max.domain.Command" resultMap="Command">
- select a.Id C_ID,a.name,a.description,b.content,b.Id,b.commandId from command a left join content b on a.Id=b.commandId where 1=1
- <if test="name !=null and !"".equals(name.trim())">
- and a.name=#{name}
- </if>
- <if test="description !=null and !"".equals(command.trim())">
- <span style="white-space:pre"> </span>and a.description like '%' #{description} '%'
- <span style="white-space:pre"> </span></if>
- </select>
- </mapper>
同样是结合OGNL和EL表达式,传入command实体作为参数,获取command中name和description属性,联合查询。
标题中动态也就是通过OGNL标签进行判断,传入参数属性是否为空,拼接sql进行查询。这与我们平时拼写组合查询sql类似,更多的也就是考验大家的sql掌握的程度了。
回到开篇,对比于hibernate封装的实体关系标签和hql语句,mybatis映照实体属性,利用特有的标签对应实体关系进行配置,跟hibernate其实本质上并无区别,但由于标签、标签属性都比较简单容易理解,所以相对也让人容易接受。而查询sql也是我们最熟悉的原生sql,然而应对传递参数的问题,mybatis利用OGNL标签进行判断拼接,熟悉OGNL和mybatis定义的获值方式也是很容易实现的。
怎么样,四不四很简单