(一)以订单为中心一对一查询
订单表:
用户表:
/* (a) 以订单为中心时,一个订单只对应一个用户,一对一
* 若果在收集结果集时只想返回一个对象,那么此时在订单对象中创建
* 一个用户对象
*
* (b)以用户为中心时,一个用户可以对应多个订单,一对多
* 如果在收集结果集时只想返回一个对象,那么此时在用户对象中应该增加
* 一个list集合
*
* inner join:内关联,查出左右两张表公共关联的部分
* left join: 左关联查询,以左边的表为中心,左边表的字段全查出来,
* 右边的表只查关联的的字段
* right join:与左关联相反
* full join:左右两张表全查出来,不论是否关联
*
* */
(1)Orders.java
package cn.shu.pojo;
import java.io.Serializable;
import java.util.Date;
public class Orders implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private Integer userId;
private String number;
private Date createtime;
private String note;
/*以订单为中心时,一个订单只对应一个用户,一对一
*
* 若果在收集结果集时只想返回一个对象,那么此时在订单对象中创建
* 一个用户对象
//附加对象
private User user;
/*setters and getters*/
(2)User.java
package cn.shu.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
//实现序列化接口
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String sex;
private Date birthday;
private String address;
/*getters and setters*/
(3)sqlMapperConfig.xml
(4)OrderMapper.java
package cn.shu.mapper;
import java.util.List;
import cn.shu.pojo.Orders;
public interface OrderMapper {
//一对一关联查询,以订单为中心关联用户
public List selectOrders();
}
(5)OrderMapper.xml
(6)测试类
//一对一查询
@Test
public void testOrdersList() throws Exception {
// 加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
// 创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//sqlSession帮助生成实现类(给接口,接口遵循四大原则)
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
List selectOrdersList = orderMapper.selectOrders();
for (Orders orders : selectOrdersList) {
System.out.println(orders);
}
}
结果:
(二)以用户为中心一对多查询
(1)User.java
package cn.shu.pojo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable{
//实现序列化接口
private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String sex;
private Date birthday;
private String address;
//附加对象
private List ordersList;
/*getters and setters*/
(2)UserMapper.java
//一对多查询
public List findListOrdersByUser();
(3)UserMapper.xml
(4)sqlMapperConfig.xml
(5)测试类
//一对多查询
@Test
public void test7() throws Exception {
// 加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
// 创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List findListOrdersByUser = userMapper.findListOrdersByUser();
for (User user : findListOrdersByUser) {
System.out.println(user);
}
}
控制台输出结果: