mybatis plus多表一对多查询
时间: 2024-01-24 12:15:35 浏览: 29
MyBatis Plus提供了多种方式来实现多表一对多查询,以下是其中一种常用的方法:
1. 使用@ManyToOne注解和@OneToMany注解来建立一对多关系。
```java
// 父表实体类
public class ParentEntity {
// 父表主键
@TableId
private Long id;
// 父表其他属性
// 子表集合
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<ChildEntity> children;
// getter和setter方法
}
// 子表实体类
public class ChildEntity {
// 子表主键
@TableId
private Long id;
// 子表其他属性
// 父表外键
@ManyToOne
@JoinColumn(name = "parent_id")
private ParentEntity parent;
// getter和setter方法
}
```
2. 在Mapper接口中使用@Select注解来编写SQL查询语句。
```java
@Mapper
public interface ParentMapper extends BaseMapper<ParentEntity> {
@Select("SELECT * FROM parent WHERE id = #{id}")
@Results({
@Result(property = "id", column = "id"),
// 其他属性映射
@Result(property = "children", column = "id",
many = @Many(select = "com.example.ChildMapper.getByParentId"))
})
ParentEntity getById(Long id);
}
@Mapper
public interface ChildMapper extends BaseMapper<ChildEntity> {
@Select("SELECT * FROM child WHERE parent_id = #{parentId}")
List<ChildEntity> getByParentId(Long parentId);
}
```
3. 在Service层调用Mapper接口的方法来实现查询。
```java
@Service
public class ParentService {
@Autowired
private ParentMapper parentMapper;
public ParentEntity getById(Long id) {
return parentMapper.getById(id);
}
}
```
通过以上步骤,你可以实现MyBatis Plus的多表一对多查询。你可以根据具体的业务需求来调整实体类和SQL查询语句。