当前位置: 代码迷 >> Java Web开发 >> mybatis 关联查询有关问题
  详细解决方案

mybatis 关联查询有关问题

热度:102   发布时间:2016-04-14 20:43:47.0
mybatis 关联查询问题
才开始学习mybatis ,看了别人的例子有几个问题


<resultMap type="Student" id="getStudentAndGroup" >  
        <id column="id" property="id"/>  
        <result column="name" property="name"/>  
        <result column="birth" property="birth"/>  
        <association property="group" column="group_id" javaType="Group">  
            <id column="g_id" property="id"/>  
            <result column="g_name" property="name"/>  
            <result column="g_position" property="position"/>  
        </association>  
    </resultMap>  
    <select id="many2one" resultMap="getStudentAndGroup" parameterType="int" >  
        select s.id,s.name,s.birth,s.group_id,g.g_id,g.g_name,g.g_position   
        from student s   
        left join g_group g on s.group_id = g.g_id  
        where s.id = #{id}  
    </select> 


如果我想取g_group 里面所有字段, association 里面我需要把所有字段都的result 都写出来嘛?

另外select 语句 能否写成 
select s.id,s.name,s.birth,s.group_id,g.*  from student s   
        left join g_group g on s.group_id = g.g_id  
        where s.id = #{id}  这样?
或者
select * from student s   
        left join g_group g on s.group_id = g.g_id  
        where s.id = #{id}  
------解决思路----------------------
可以的 ,只要sql是合法的,resultMap配置的时候,配置对就可以了
------解决思路----------------------
只要sql合法就可以,不过,如果你写了* ,就需要在resultMap中将表中对应的字段都写上。不然mybatis会因为找不到对应的属性而报错的。
  相关解决方案