Mybatis多表联合查询,嵌套查询,动态SQL
Mybatis多表联合查询
一对一
一对一查询:通过一方关联查询出另外一方的关系数据
- 创建数据库和相关数据表
- 创建需要关联查询的实体类,里面包含相关的属性
//丈夫查妻子
public class Husband {
private Integer id;
private String name;
private Wife wife;
}
public class Wife {
private Integer id;
private String name;
}
- 编写
HusbandMapper
接口,为了调用方法
public interface HusbandMapper {
List<Husband> findByName(String name);
}
- 编写相关的Sql语句
- 关联查询的时候需要用
resultMap
进行自定义标签的映射 - 非关联单表查询的时候可以直接使用
resultType
进行查询 property
表示属性对应的是实体类的字段名称column
表示的是自己定义的属性值,与sql语句定义的字段名称相同association
和javaType
在一对一关联查询的时候使用association
里映射的是被关联查询的表和属性值
- 关联查询的时候需要用
<resultMap id="husbandAndWife" type="husband">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="wife" javaType="wife">
<id property="id" column="wid"/>
<result property="name" column="wname"/>
</association>
</resultMap>
<select id="findByName" parameterType="string" resultMap="husbandAndWife">
select h.id,h.name,w.id wid, w.name wname from t_husband h,t_wife w
where h.id = w.id and h.name = #{name}
</select>
- 编写
HusbandMapperTest
测试类
public class CustomerMapperTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
//加载核心配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config");
//创建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test(){
//打开会话工厂
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取内容
CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
//遍历Customer表数据
List<Customer> ret = mapper.findByName("aa");
//输出
System.out.println(ret);
}
一对多
一个用户可以关联查询出自己的订单信息
- 创建数据库和相关数据表
- 创建需要关联查询的实体类,里面包含相关的属性
public class Customer {
private Integer id;
private String name;
private List<Order> orders;
}
public class Order {
private Integer id;
private String goods;