附加:
数据库字段和自定义对象属性相对应即可
二、MyBatis的嵌套查询
什么是嵌套查询
嵌套查询就是将原来多表查询中的联合查询语句拆成单个表的查询,再使用MyBatis的语法嵌套在一起。
(一)一对一的嵌套
需求:查询一个订单,与此同时查询出该订单所属的用户
代码实现
1、OrdersMapper接口中定义方法
public interface OrderMapper {
public List<Order> findAllWithUser();
}
2、OrderMapper.xml映射
<!--一对一嵌套查询-->
<resultMap id="orderMap" type="orders">
<id column="oid" property="oid"></id>
<result column="dis" property="dis"></result>
<!--根据订单中cus_fk外键,查询用户表数据-->
<association
property="customer"
javaType="com.offcn.bean.Customer"
column="cus_fk"
select="com.offcn.mapper.CustomerMapper.findById"
</association>
</resultMap>
<select id="findAllWithCustomer" resultMap="orderMap" >
SELECT * FROM orders
</select>
3、CustomerMapper接口
Customer findById(Integer cid);
4、CustomerMapper.xml 映射
<select id="findById" parameterType="int" resultType="com.offcn.bean.Customer">
SELECT * FROM `customer` where cid = #{cid}
</select>
5、测试代码
@Test
public void testOrderWithCustomer() throws Exception {
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
List<Order> list = orderMapper.findAllWithCustomer();
for (Order order : list) {
System.out.println(order);
}
}
(二)一对多的嵌套
需求:查询一个用户,与此同时查询出该用户具有的订单
1、CustomerMapper接口并定义方法
public Customer getInfoByName( @Param("name") String name);
2、CustomerMapper.xml映射文件
<resultMap type="Customer" id="newCustomer">
<id property="cid" column="cid"/>
<result property="name" column="name"/>
<collection
property="orders"
column="id"
ofType="com.offcn.bean.Orders"
select="com.offcn.mapper.OrdersMapper.getOneByfk">
</collection>
</resultMap>
<select id="getInfoByName" resultMap="newperson">
SELECT c.*FROM customer c WHERE c.name=#{name};
</select>
3、OrdersMapper接口
public Orders getOneByfk(int fk);
4、OrdersMapper.xml的映射文件
<select id="getOneByfk" resultType="com.offcn.bean.Orders">
select * from orders where cus_fk=#{cusid}
</select>
5、测试代码
@Test
public void testOrderWithCustomer() throws Exception {
CustomerMapper customerMapper= sqlSession.getMapper(CustomerMapper.class);
Customer customer = customerMapper.getInfoByName(“张三”);
System.out.println(customer );
}