今天使用Mybatis一对一关联查询时候出现一个问题,只能查出关联表主键,无法查询出关联表中的其他数据:
Mybatis的代码:
<mapper namespace="com.usc.user.mapper.UserMapper"> <resultMap type="UserBean" id="UserInfoMap"> <id property="id" column="id" /> <result property="username" column="username" /> <result property="password" column="password" /> <result property="roleId" column="roleId" /> <association property="role" select="queryRoleInfoById" column="roleId" > <id property="roleId" column="roleId" /> <result property="rolename" column="role_name" /> </association> </resultMap>
<!-- 用户登录 --> <select id="validateUser" resultMap="UserInfoMap" parameterType="UserBean"> SELECT * FROM User WHERE username=#{username} and password=#{password} </select>
<!-- 查询用户角色 --> <select id="queryRoleInfoById" resultType="RoleInfoBean"> SELECT * FROM role_info WHERE roleId=#{roleId} </select> |
数据库结构:
查询结果:
{"id":1,"username":"11","password":"22","roleId":2,"role":{"roleId":2,"rolename":null}}
|
最后弄了半天才发现原来关联查询的那个对象的属性名必须和数据库中的字段名一样。即:
Rolename字段在数据库中也是这个名字。
或者将查询改为:
<!-- 查询用户角色 --> <select id="queryRoleInfoById" resultType="RoleInfoBean"> SELECT roleId roleId,role_name rolename FROM role_info WHERE roleId=#{roleId} </select> |
改完之后的查询结果如下:
{"id":1,"username":"11","password":"22","roleId":2,"role":{"roleId":2,"rolename":"副站长"}}
|