一 概述
- 两种方式
(1)resultType(多用)
(2)resultMap
二. 实例代理
用户表和订单表
例子:查询所有订单,订单为主表,一对一
查询客户的订单 ,客户为主表,一对多
代码目标:查询指定订单和关联客户的姓名和地址
步骤:核心是sql语句
1. 写出sql语句
select o.id,o.number,o.createtime,o.note,u.username,u.address from orders o LEFT JOIN user u on o.user_id=u.id
2. 写对应的pojo类
public class OrderWithCutomer extends Orders {
private String username;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "OrderWithCutomer [username=" + username + ", address=" + address + "]";
}
}
3. 映射文件配置sql语句
<!-- 对应的是查询结果的列名(id),不是发送的sql语句(o.id) -->
<select id="findOrderWithCustomer" parameterType="int" resultType="OrderWithCutomer">
select
o.id,
o.number,
o.createtime,
o.note,
u.username,
u.address
from orders o
LEFT JOIN user u
on o.user_id=u.id and o.id=#{id}
</select>
4. 接口定义相关方法
public interface OrdersDao {
public List<OrderWithCutomer> findOrderWithCustomer();
}
5. 测试
public class OrdersMapperTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void setSqlSession() throws Exception{
//1.获得SqlSession对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
}
@Test
public void testFindOrderWithCustomer() throws Exception{
//1.获得SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.获得接口的代理对象 sqlSession.getMapper()
OrdersDao ordersDao = sqlSession.getMapper(OrdersDao.class);
//3.使用代理对象的方法操作
List<OrderWithCutomer> orderWithCustomerList = ordersDao.findOrderWithCustomer(5);
for (OrderWithCutomer orderWithCustomer : orderWithCustomerList) {
System.out.println(orderWithCustomer.getUsername()+ +orderWithCustomer.getId());
}
//4.释放资源
sqlSession.close();
}
}