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();
    }
}

标签: none

入群须知:

凡是加入我群者,皆要严守群规,每周六、日是群规反思日。群规的要义有三点∶

(1)坚持系统化的学习方式,由量变到质变。仅仅解决工作中的问题,并不叫系统化的学习。

(2)坚持以价值为导向的学习方式,扔掉低价值知识[配置、调参、安装],聚焦高价值知识[结构、算法、优化],推动量变到质变的进程。

仅有一条评论

  1. borjja borjja

    这里的sql是多表查询吧,多对多关系是有中间表的,你直接在关联表里面查询吗?

添加新评论