1、映射接口
public interface ArticleMapper
{
@Select("SELECT * FROM tb_article WHERE id IN (SELECT article_id FROM tb_item WHERE order_id = #{id} ) ")
List<Article> selectByOrderId(Integer order_id);
}
public interface OrderMapper
{
@Select("SELECT * FROM tb_order WHERE ID = #{id}")
@Results(
{ @Result(id = true, column = "id", property = "id"), @Result(column = "code", property = "code"),
@Result(column = "total", property = "total"),
@Result(column = "user_id", property = "user", one = @One(select = "cn.mybatis.mydemo6.mapper.UserMapper.selectById", fetchType = FetchType.EAGER)),
@Result(column = "id", property = "articles", many = @Many(select = "cn.mybatis.mydemo6.mapper.ArticleMapper.selectByOrderId", fetchType = FetchType.LAZY)) })
Order selectById(Integer id);
}
public interface UserMapper
{
@Select("SELECT * FROM tb_user WHERE ID = #{id} ")
User selectById(Integer id);
}
2、引入映射接口
<mappers>
<mapper class="cn.mybatis.mydemo6.mapper.ArticleMapper" />
<mapper class="cn.mybatis.mydemo6.mapper.OrderMapper" />
<mapper class="cn.mybatis.mydemo6.mapper.UserMapper" />
</mappers>
3、测试代码
public class App
{
public static void main(String[] args)
{
// 获取Session实例
SqlSession session = MySqlSessionFactory.getSqlSession();
// 获取OrderMapper实例
OrderMapper om = session.getMapper(OrderMapper.class);
// 根据id查询Order对象
Order order = om.selectById(1);
// 查看查询到的Order对象
System.out.println(order.getId() + " " + order.getCode() + " " + order.getTotal());
// 查看Order关联的User对象
System.out.println(order.getUser());
// 查看关联的Article集合,因为配置使用的是LAZY懒加载,所以当使用时才执行SQL语句
order.getArticles().forEach(article -> System.out.println(article));
// 提交事务
session.commit();
// 关闭Session
session.close();
}
}