mybatis嵌套关联查询如下:
由于我的是一对集合查询,所以我有两个类。
@Data
@TableName("tb_user")
public class User {
@TableId(type= IdType.INPUT)
private String id;
@TableField("user_name")
private String username;
private String password;
private String name;
private String email;
private int age;
private ArrayList<Authority> list;
}
权限类
@Data
@TableName
public class Authority {
@TableId(type = IdType.INPUT)
@TableField("aid")
private int id;
@TableId("aname")
private String name;
}
测试类
@Test
public void ManyToMany(){
User user = userMapper.selectAuthorityById(1);
ArrayList <Authority> list = user.getList();
System.out.println(user);
for (Authority authority : list) {
System.out.println("所对应权限为"+authority.getName());
}
}
springboot项目的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis plus 起步依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
这下面就是我xml文件里面怎么写的嵌套查询语句
<mapper namespace="com.itheima.mybatisplus.mapper.UserMapper">
<!--返回的对象为authority-->
<resultMap id="authority" type="com.itheima.mybatisplus.domain.User">
<id column="id" property="id"/>
<id column="password" property="password"/>
<id column="age" property="age"/>
<id column="email" property="email"/>
<id column="name" property="name"/>
<id column="user_name" property="username"/>
<collection property="list"
ofType="com.itheima.mybatisplus.domain.Authority">
<id property="id" column="aid"/>
<id property="name" column="aname"/>
</collection>
<select id="selectAuthorityById" parameterType="int" resultMap="authority">
SELECT * FROM
authority a,tb_user t,user_authority ua
WHERE a.aid=ua.authority_id
AND t.id=ua.user_id
AND t.id=#{id}
</select>
数据库的配置我就不放了,直接编写就可以了,看会下面这个xml配置就可以了
版权声明:本文为weixin_52366309原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。