Mybatis关联查询与常见问题解决

用户实体类User

public class User implements Serializable {

    private Integer id;
    private String username;
    private String password;
    private Date birthday;
    private String address;

    public User() {
    }
    public User(String username, String password, Date birthday, String address) {
        this.username = username;
        this.password = password;
        this.birthday = birthday;
        this.address = address;
    }
    get、set、toString方法
}

订单实体类Order

public class Order implements Serializable{
    private int id;
    private Date createTime;
    //支付方式 0:支付宝 1:微信
    private int channel;
    //支付金额
    private int payment;
    //支付状态 0:待支付 1:未支付 2:已支付
    private int status;

    public Order(Date createTime, int channel, int payment, int status) {
        this.createTime = createTime;
        this.channel = channel;
        this.payment = payment;
        this.status = status;
    }
    public Order() {
    }
    get、set、toString方法
}

1、单向多对一关联查询

多个订单关联一个客户
在订单实体类中添加用户实体对象,并在数据库表t_order中添加字段user_id作为外键。

Order实体类添加

    //订单关联客户 manyToOne
    private User user;
    get,set方法,修改toString方法

订单表如下:
这里写图片描述
用户表如下:
这里写图片描述

订单sql映射文件Order.xml中添加

<resultMap type="Order" id="order2">
        <id column="id" property="id"/>
        <result column="create_time" property="createTime"/>
        <result column="channel" property="channel"/>
        <result column="payment" property="payment"/>
        <result column="status" property="status"/>
        <!--association :配置多对一属性(或一对一)
            property:order里面的User属性名
            javaType:属性类型(这里是用户类型)
        -->
        <association property="user" javaType="User">
        <!-- id:声明主键,表示user_id是关联查询对象的唯一标识-->
            <id column="user_id" property="id"/>
            <result column="username" property="username"/>
            <result column="password" property="password"/>
            <result column="birthday" property="birthday"/>
            <result column="address" property="address"/>
        </association>
    </resultMap>

即使字段和属性一样的都要写出来不能省略,不然会不查出来。只会查自己写的要查的字段,其他的字段就算写在了result里面也是不会查出来的。

mapper映射文件OrderMapper中添加方法

public interface OrderMapper {
    public Order findByIdWithManyToOne(int id);
}

测试:

public class OrderMapperTest {

        InputStream inputStream;
        SqlSession session;
        @Before
        public void init() throws Exception{
            String resource = "sqlMapConfig.xml";
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = ssfb.build(inputStream);
            session = sqlSessionFactory.openSession();
        }
        @After
        public void destroy() throws Exception{
            inputStream.close();
            session.close();
        }
        @Test
        public void testFindByIdWithManyToOne(){
            OrderMapper mapper = session.getMapper(OrderMapper.class);
            Order order = mapper.findByIdWithManyToOne(1);
            System.out.println(order);
        }
}

输出:

Order [id=1, createTime=Sat Sep 02 13:21:30 CST 2017, channel=1, payment=999, status=0, user=User [id=1, username=小红, password=123456, birthday=Sat Sep 02 00:00:00 CST 2017, address=安徽合肥, orders=[]]]

如果只查两张表中某一些字段,也可以自定义一个pojo来进行封装。
比如要查订单表的id,支付金额,以及关联用户的id和用户名。

自定义类型

public class BasicDo {
    private int order_id;
    private int payment;
    private int user_id;
    private String username;
    getset、toString方法
}

映射文件Order.xml中

<select id="findByIdWithPojo" parameterType="int" resultType="BasicDo">
        SELECT 
        o.id order_id,
        o.payment,
        u.id user_id,
        u.username
        FROM t_order o 
        LEFT OUTER JOIN t_user u ON o.user_id=u.id 
        WHERE o.id=#{id}
    </select>

测试:

    @Test
        public void testFindByIdWithPojo(){
            OrderMapper mapper = session.getMapper(OrderMapper.class);
            BasicDo pojo = mapper.findByIdWithPojo(1);
            System.out.println(pojo);
        }

输出:

BasicDo [order_id=1, payment=999, user_id=1, username=小红]

2、单向一对多查询
一个用户可以有多个订单
现在订单表和用户表如下
这里写图片描述
这里写图片描述
用户sql映射文件User.xml中

<!-- 一对多查询 -->
    <select id="findByWithOneToMany" parameterType="int" resultMap="user2">
        SELECT 
        *
        FROM t_user u LEFT OUTER JOIN t_order o
        ON o.user_id = u.id
        WHERE u.id=#{id}
    </select>
    <resultMap type="User" id="user2">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="birthday" property="birthday"/>
        <result column="address" property="address"/>
        <collection property="orders" ofType="Order">
            <id column="id" property="id"/>
            <result column="create_time" property="createTime"/>
            <result column="channel" property="channel"/>
            <result column="payment" property="payment"/>
            <result column="status" property="status"/>
        </collection>
    </resultMap>

mapper接口UserMapper中添加对应方法

public User findByWithOneToMany(int id);

测试:

@Test
    public void testFindByWithOneToMany(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.findByWithOneToMany(1);
        System.out.println(user);
    }

输出结果

User [id=1, username=小红, password=123456, birthday=Sat Sep 02 00:00:00 CST 2017, address=安徽合肥, orders=[Order [id=1, createTime=Fri Sep 01 13:15:30 CST 2017, channel=1, payment=888, status=0, user=null]]]

明显错误了,关联的Order的id应该是2而不是1(当成了用户id处理了),而且这里有两个关联的Order,但是也只能列出来第一条。
出现这种错误的原因是两个实体类主键都为id,如果不明确指定那么框架是不能区分的。
解决办法:这里给出个更通用点的,防止弄混那么可以不需要用关联字段user_id,如果主键名一样那么不要用SELECT * ,同时主键需要取别名。
修改如下

<!-- 一对多查询 -->
    <select id="findByWithOneToMany" parameterType="int" resultMap="user2">
        SELECT 
        u.id u_id,
        u.username,
        u.password,
        u.birthday,
        u.address,
        o.id order_id,
        o.payment,
        o.create_time,
        o.channel,
        o.status
        FROM t_user u LEFT OUTER JOIN t_order o
        ON o.user_id = u.id
        WHERE u.id=#{id}
    </select>
    <resultMap type="User" id="user2">
        <id column="u_id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="birthday" property="birthday"/>
        <result column="address" property="address"/>
        <collection property="orders" ofType="Order">
            <id column="order_id" property="id"/>
            <result column="create_time" property="createTime"/>
            <result column="channel" property="channel"/>
            <result column="payment" property="payment"/>
            <result column="status" property="status"/>
        </collection>
    </resultMap>

这里讲各自的id都取了别名u_id和order_id至于user_id就不需要去理睬了(虽然可以把user_id作为用户的id但是容易弄混乱)。
测试结果:

User [id=1, username=小红, password=123456, birthday=Sat Sep 02 00:00:00 CST 2017, address=安徽合肥, orders=[Order [id=2, createTime=Fri Sep 01 13:15:30 CST 2017, channel=1, payment=888, status=0, user=null], Order [id=3, createTime=Sat Sep 02 19:45:29 CST 2017, channel=1, payment=777, status=0, user=null]]]

id为2和3的订单都列了出来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值