Mybatis-多表查询
一、一对一查询
<mapper namespace="com.finnlee.mapper.OrderMapper"> <resultMap id="orderMap" type="com.finnlee.pojo.Order"> <result column="uid" property="user.id"></result> <result column="username" property="user.username"></result> <result column="password" property="user.password"></result> <result column="birthday" property="user.birthday"></result> </resultMap> <select id="findAll" resultMap="orderMap"> select * from orders o,user u where o.uid=u.id </select> </mapper>
<resultMap id="orderMap" type="com.finnlee.pojo.Order"> <result property="id" column="id"></result> <result property="ordertime" column="ordertime"></result> <result property="total" column="total"></result>
<!-- property="user" 当前实体属性名 javaType="com.finnlee.pojo.User" 当前实体属性类型 --> <association property="user" javaType="com.finnlee.pojo.User"> <result column="uid" property="id"></result> <result column="username" property="username"></result> <result column="password" property="password"></result> <result column="birthday" property="birthday"></result> </association> </resultMap>
二、一对多|多对多查询
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.finnlee.mapper.MemberMapper"> <resultMap id="memberMap" type="com.finnlee.pojo.Member"> <id column="id" property="id"></id> <result column="username" property="username" ></result> <collection property="orderList" ofType="com.finnlee.pojo.Order" > <result column="order_id" property="id"></result> <result column="order_sn" property="order_sn"></result> </collection> <collection property="roleGroup" ofType="com.finnlee.pojo.RoleGroup" > <result column="title" property="title"></result> </collection> </resultMap> <select id="findAll" resultMap="memberMap"> select a.id,a.username ,b.order_sn ,b.id AS order_id,c.title from `member` a LEFT JOIN `order` b ON a.id = b.mid LEFT JOIN role_group c ON a.id = c.mid </select> </mapper>