A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

今天是我们Mybatis框架学习的第3天,今天要求大家整理的内容是,
1.Mybatis的一对一查询
2.Mybatis的一对多查询
3.Mybatis的多对多查询
4.动态sql及例子

2 个回复

倒序浏览
1.Mybatis的一对一查询方法一:创建一个PO对象实体类,继承主表,把要联查的表的字段作为属性封装进PO对象中,并在ToString方法中,调用父类的ToString方法,进行字符串拼接;


方法二:在主表的实体类中,添加需要联查的表的实体类作为属性值,这样查询出的结果会被封装进主表中;

2.Mybatis的一对多查询
在主表中添加一个属性为多表的对象集合,这样查询的结果会被封装进对象中;
配置文件中需要定义<resultType>标签,定义完主表的属性后用<association>类定义集合对象,并且要指定javaType的类型,用于返回结果封装;
<resultMap id="AccountUser" type="account" >
    <id property="id" column="id" />
    <result property="uid" column="uid" />
    <result property="money" column="money"/>
    <association property="user" javaType="user">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="address" column="address"/>
        <result property="sex" column="sex" />
        <result property="birthday" column="birthday"/>
    </association>
</resultMap>
3.Mybatis的多对多查询
多对多查询可以从任意一张表的角度看成是一对多,这样的话,将需要作为主表的实体类中添加需要联查的表的对象集合,但是使用<collection>标签作为连接;
<resultMap id="UserRoleMap" type="user">
    <id property="id" column="id" />
    <result property="username" column="username"/>
    <result property="address" column="address"/>
    <result property="sex" column="sex"/>
    <result property="birthday" column="birthday"/>
    <collection property="roles" ofType="role">
        <id property="id" column="rid"></id>
        <result property="roleName" column="role_name"/>
        <result property="roleDesc" column="role_desc"/>
    </collection>4.动态sql及例子

<if>标签, test属性值跟着表达式,如果表达式成立,那么<if>标签中的内容会被拼接到sql语句中,根据表达式的非空判断,来确定是否要添加查询条件,实现动态sql;
<where>标签, 如果where标签内容被拼接,那么会提前在sql语句中添加上where true ,where标签中的内容要以and 来连接where标签;
<foreach>标签,将类型为集合的参数遍历,一个个的取出集合中的值,与属性定义的字符串一起拼接,<foreach>标签的属性open,close,item,separator属性共同定义了需要拼接的字符串;
<sql>标签,将重复使用的sql语句片段提前出来,放入<sql>标签中,需要用到时使用<include >标签插入;
例子:User表和Account表联查, 在User的实体类中,添加Account属性,sql语句为 select * from user u ,account a where u.id = a.uid;

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马