【1】直接步入正题,我们先看一下我们的多表结构
【2】我们可以看到user_role关联了两个外键。
如果我们想通过users顺便把role查出来怎么办?
【3】有经验的小伙伴一定知道,在创建users实体类的时候,还会创建一个role类,并且在users类中把role类当作成员变量写入。
【4】那么sql语句怎么写呢,我利用的时mybatis的注解方法写sql语句,首先需要配置user类的成员变量和数据库中的对应名称。
用@Results注解,写入我们数据库和实体类中对应的字符串,最后一个@Result就是我们要的role数据,我们通过表结构可以看到是一个多对多的关系,所以用@Many注解,选择roleDao中的findByuserId方法,接下来就是,怎么通过UserId把role查出来
@Repository
public interface IUserDao {
@Select("select * from users where username=#{username}")
@Results(id = "Users" ,value = {
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "email",column = "email"),
@Result(property = "password",column = "password"),
@Result(property = "phoneNum",column = "phoneNum"),
@Result(property = "status",column = "status"),
@Result(property = "roles",column = "id",many=@Many(select="com.itheima.ssm.dao.IRoleDao.findByUsersId"))
})
public UserInfo findByUserName(String username);
}
【5】通过UserId把role查询出来解析,
我们可以看到Users和Role之间存在一个中间表,并不是通过外键直接连接。所以用左外连接查询比较麻烦,需要写两个left outer join。应该是利用in,role的id就在多表中。
@Select("select * from role where id in ( select roleId from users_role where userId=#{userId} ) ")
public List findByUsersId(String userId);



