mybatis中resultMap的用法

新建User,role,Permission三个实体类

User类

       private Integer uId;
	
	private String  userName;
	
	private String password;
	
	private Set<Roles> role = new HashSet<Roles>();


Roles 类


private Integer rId;
	
	private String name;
	
	private Set<Permission> permissions = new HashSet<Permission>();

private Set<User> user = new HashSet<User>();


Permission类

private Integer pId;
	
	private String name;
	
	private String url;

其中user包含了role的集合,并且role包含了permission的集合

当我们想以user_name为关键字查询时,sql的写法

<resultMap type="User" id="userMap">
		<id property="uId" column="id"/>
		<result property="userName" column="userName" />
		<result property="password" column="password"/>
		<collection property="role" ofType="Roles">
			<id property="rId" column="rId"/>
			<result property="name" column="name"/>
			<collection property="permissions" ofType="Permission">
				<id property="pId" column="pId"/>
				<result property="name" column="pName"/>
				<result property="url" column="url"/>
			</collection>
		</collection>
	</resultMap>


其中<collection property="role" ofType="Roles">中的role要和user实体类中private Set<Roles> role = new HashSet<Roles>();  名称保持一致

ofType="Roles"表示对应的实体类


<select id="findByUserName" parameterType="String" resultMap="userMap">
		select 
			a.id AS "id",
			a.user_name AS "userName",
			a.password AS "password",
			r.id AS "rId",
			r.name AS "name",
			p.id AS "pId",
			p.name AS "pName",
			p.url AS "url"
		from user a
		inner join user_role ur on ur.uId = a.id
		left join role r on r.id = ur.rId
		left join permission_role pr on pr.rId  = r.id 
		left join permission p on p.id = pr.pId
		where a.user_name = #{0}
	</select>


注意:sql中的别名要和column中的保持一致

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值