美文网首页
2018-02-16-2.mybatis一对一映射情况解析

2018-02-16-2.mybatis一对一映射情况解析

作者: 简单coder | 来源:发表于2018-02-16 23:03 被阅读20次

    junit测试类代码:(调用接口)

    private SqlSessionFactory ssf = null;
        @Before
        public void before() throws Exception {
            InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
            this.ssf = new SqlSessionFactoryBuilder().build(is);
        }
    
        @Test
        public void aaa() {
            SqlSession sqlSession = this.ssf.openSession();
    
            OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
    
            List<Orders> orders = mapper.selectAllOrdersWithUser();
    
            for (Orders order :
                    orders) {
                System.out.println(order);
            }
        }
    

    接口mapper类代码:

    /**
     * Created by syk on 2018/2/16.
     */
    public interface OrderMapper {
    
        public List<Orders> selectAllOrders();
    
    
        //多对一
    
        public List<Orders> selectAllOrdersWithUser();
    }
    
    

    接口对应的xml文件代码:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
    
    
    
    
    <mapper namespace="cn.itcast.mapper.OrderMapper">
        <resultMap id="ordersList" type="Orders">
            <result property="user_id" column="userId"></result>
        </resultMap>
    
        <select id="selectAllOrders" resultMap="ordersList">
            SELECT id,user_id,number,createtime,note FROM orders
        </select>
    
        <resultMap id="allOrdersWithUser" type="Orders">
            <result column="user_id" property="userId"/>
            <result column="id" property="id"/>
            <result column="number" property="number"/>
            <result column="createtime" property="createtime"/>
            <result column="note" property="note"/>
            <association property="user" javaType="User">
                <result column="user_id" property="id"/>
                <result column="username" property="username"/>
            </association>
        </resultMap>
        <select id="selectAllOrdersWithUser" resultMap="allOrdersWithUser">
            select
            o.*,
            u.*
            from orders o
            LEFT JOIN user u
            on o.user_id = u.id;
        </select>
    
    

    需要注意的是:在一对一情况,对象中嵌套了另外一个对象,那么resultMap映射关系中正常可以忽略的属性都不能够忽略,否则无法成功映射

    相关文章

      网友评论

          本文标题:2018-02-16-2.mybatis一对一映射情况解析

          本文链接:https://www.haomeiwen.com/subject/kuaptftx.html