public interface MyBaseMapper<T> extends Mapper<T>, MySqlMapper<T>,MyInsertListMapper<T> { }和public interface AdvertMapper extends MyBaseMapper<Advert> { }如何关联查询
时间: 2023-12-10 10:03:38 浏览: 38
关联查询的实现需要根据具体的业务需求来确定,一般可以使用MyBatis的XML配置文件或注解方式实现。以下是一个简单的示例,假设我们有两个实体类Advert和User,其中Advert中包含一个userId属性,表示该广告是由哪个用户发布的。我们可以通过关联查询,将该广告对应的用户信息一起查询出来。
首先,在AdvertMapper接口中定义一个查询方法,使用@Results注解将查询结果映射到Advert和User对象中:
```
@Select("SELECT a.*, u.username, u.age FROM advert a LEFT JOIN user u ON a.userId = u.id WHERE a.id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "title", column = "title"),
@Result(property = "userId", column = "userId"),
@Result(property = "user.username", column = "username"),
@Result(property = "user.age", column = "age")
})
Advert findAdvertWithUserById(Long id);
```
接下来,在Advert实体类中定义一个User对象,用于接收查询结果:
```
public class Advert {
private Long id;
private String title;
private Long userId;
private User user;
// 省略getter和setter方法
}
```
最后,在User实体类中定义相应的属性和方法:
```
public class User {
private Long id;
private String username;
private Integer age;
// 省略getter和setter方法
}
```
这样,我们就可以通过调用AdvertMapper中的findAdvertWithUserById方法,同时查询出对应的广告和用户信息。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)