一个客户多个订单,客户类一面有一个订单集合
package com.cd; import java.util.List; public class Customer { private int id; String name; List<Order> orders; public Customer() { super(); } public Customer(int id, String name, List<Order> orders) { super(); this.id = id; this.name = name; this.orders = orders; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Order> getOrders() { return orders; } public void setOrders(List<Order> orders) { this.orders = orders; } }
<?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.cd.CustomerMapper"> <resultMap type="Customer" id="myCustomer"> <id property="id" column="id" /> <result property="name" column="c_name" /> <collection property="orders" ofType="Order"> <id column="id" property="id"/> <result column="o_name" property="name"/> </collection> </resultMap> <select id="selectCustomerByOrderId" resultMap="myCustomer" resultType="Customer"> select c.id, c.name as c_name, o.name as o_name from customer_tbl as c left join order_tbl as o on c.id = o.cid where c.id=#{id} </select> </mapper>
package com.cd; import java.util.List; public interface CustomerMapper { public List<Order> selectOrders(); public Customer selectCustomerByOrderId(int id); }
package com.cd; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class Test { public static void main(String[] args) { String resource = "com/cd/mybatis-config.xml"; InputStream inputStream; try { inputStream = (InputStream) Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sqlSessionFactory.openSession(); CustomerMapper mapper = session.getMapper(CustomerMapper.class); Customer c = mapper.selectCustomerByOrderId(1); System.out.println(c); } catch (IOException e) { e.printStackTrace(); } } }
原文链接:http://codingdict.com/