1.效果
2.遇到的问题
今天遇到了一个mybatis的多对一问题
下面是表的结构
user
role
而对应的实体类
User
package cn.yf.blog.bean;
public class User {
private Integer id;
//用户账号名
private String name;
//用户密码
private String password;
//shiro加密的盐
private String salt;
//权限
private Role role;
}
Role
package cn.yf.blog.bean;
public class Role {
//权限id
private Integer role_id;
//权限名
private String role_name;
}
当我需要通过名字查询用户时,发现查询的Role为null,后面才知道,我忽略了,实体类于数据库表的对应。一个是role_id一个是Role
解决方法:使用ResultMap
<resultMap id="userResultMap" type="User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="password" property="password"/>
<result column="salt" property="salt"/>
<association property="role" javaType="Role">
<id column="role_id" property="role_id"/>
<result column="role_name" property="role_name"/>
</association>
</resultMap>
<select id="getUserByName" parameterType="String" resultMap="userResultMap">
select * from user u,role r where name = #{name} and u.role_id = r.role_id;
</select>