一. 简介:
本实例使用顾客和订单的例子做说明: 一个顾客可以有多个订单, 一个订单只对应一个顾客
二. 例子:
1. 代码结构图:
2. 建表语句:
CREATE DATABASE test; USE test; CREATE TABLE person( personId VARCHAR(36) PRIMARY KEY, personName VARCHAR(64), personAddress VARCHAR(128), personTel VARCHAR(11) ); CREATE TABLE orders( orderId VARCHAR(36) PRIMARY KEY, orderNumber VARCHAR(20), orderPrice INT, pid VARCHAR(36) ); INSERT INTO person VALUES('001', 'Jack', 'Wuhan', '1234567'); INSERT INTO orders VALUES('O_00001', '00001', 100, '001'); INSERT INTO orders VALUES('O_00002', '00002', 200, '001'); SELECT p.*, o.* FROM person p JOIN orders o ON (p.personId=o.pid) WHERE p.personId = '001'
3. 顾客实体:
/** * 客户实体 */ public class Person { private String id; private String name; private String address; private String tel; private Listorders; @Override public String toString() { return "{id: " + id + ", name: " + name + ", address: " + address + ", tel: " + tel + "}"; } }
4. 订单实体:
/** * 订单实体 */ public class Order { private String id; private String number; private int price; private Person person; @Override public String toString() { return "{id: " + id + ", number: " + number + ", price: " + price + "}"; } }
5. 一对多实体配置: Person.xml
6. 多对一实体配置:
7. 总配置: sqlMapConfig.xml
8. 测试文件:
/** * 测试一对多和多对一 */ public class MybatisTest { private SqlSessionFactory ssf; @Before public void initSF() throws Exception { String resource = "sqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); ssf = new SqlSessionFactoryBuilder().build(inputStream); } @Test//一对多关联查询 public void selectPersonById()throws Exception{ SqlSession session = ssf.openSession(); Person person = session.selectOne("com.zdp.domain.Person.selectPersonById", "001"); System.out.println(person.getOrders()); } @Test//多对一关联查询 public void selectOrderById()throws Exception{ SqlSession session = ssf.openSession(); Order order = session.selectOne("com.zdp.domain.Order.selectOrderById", "O_00001"); System.out.println(order.getPerson().getName()); } }