01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 | public class Customer { private Integer cid ; private String cname; //省略get/set/toString } /** 一个订单属于一个客户,在订单方创建客户引用 注意.客户引用的对象名字很重要 */ public class Orders { private Integer oid ; private String orderName; private String cid; private Customer c; //省略get/set/toString } |
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public interface OrdersMapper { List<Orders> findAllInfo(); } <?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.b3a4a.maybatis.mapper.OrdersMapper"> <resultMap id="order_customer" type="orders"> <id property="oid" column="oid"/> <result property="orderName" column="oname" /> <result property="cid" column="customer_id" /> <association property="c" javaType="customer"> <id property="cid" column="cid"/> <id property="cname" column="cname"/> </association> </resultMap> <select id="findAllInfo" resultMap="order_customer"> SELECT customer.*,orders.oid,orders.oname,orders.cid AS customer_id FROM orders JOIN customer ON customer.cid=orders.cid </select> </mapper> |
01 02 03 04 05 06 07 08 09 10 11 12 13 | @Test public void testFindAll() throws IOException { InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSession session = new SqlSessionFactoryBuilder().build(is).openSession(); OrdersMapper mapper = session.getMapper(OrdersMapper.class); List<Orders> orders = mapper.findAllInfo(); for (Orders order : orders) { System.out.println(order); System.out.println(order.getCustomer()); } session.close(); is.close(); } |
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="jdbcConfig.properties"></properties> <typeAliases> <package name="com.b3a4a.maybatis.domain" /> </typeAliases> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <package name="com.b3a4a.maybatis.mapper"/> </mappers> </configuration> |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |