spring boot mybatis puls 查找一个表的所有数据,并带出他对应子类的总数
时间: 2023-12-06 15:45:20 浏览: 49
假设有两个实体类 `Parent` 和 `Child`,它们之间的关系是一对多。`Parent` 对应的表名是 `parent_table`,`Child` 对应的表名是 `child_table`,它们的关系是通过 `parent_id` 字段建立的。现在我们要查询 `parent_table` 表中所有数据,并且要带出每个 `Parent` 对象对应的 `Child` 对象的总数,可以按照以下步骤进行:
1. 在 `Parent` 类中添加一个属性 `childCount`,用于存放每个 `Parent` 对象对应的 `Child` 对象的总数。
```java
public class Parent {
private Long id;
private String name;
private List<Child> children;
private Integer childCount;
// getter and setter
}
```
2. 在 `ParentMapper` 中添加一个方法,用于查询 `parent_table` 表中的所有数据,并且带出每个 `Parent` 对象对应的 `Child` 对象的总数。
```java
@Mapper
public interface ParentMapper {
@Select("SELECT * FROM parent_table")
@Results(id = "parentMap", value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "name", column = "name"),
@Result(property = "children", column = "id", many = @Many(select = "com.example.demo.mapper.ChildMapper.findByParentId")),
@Result(property = "childCount", column = "id", javaType = Integer.class, one = @One(select = "com.example.demo.mapper.ChildMapper.countByParentId"))
})
List<Parent> findAll();
}
```
3. 在 `ChildMapper` 中添加两个方法,用于查询每个 `Parent` 对象对应的 `Child` 对象的列表和总数。
```java
@Mapper
public interface ChildMapper {
@Select("SELECT * FROM child_table WHERE parent_id = #{parentId}")
List<Child> findByParentId(Long parentId);
@Select("SELECT COUNT(*) FROM child_table WHERE parent_id = #{parentId}")
Integer countByParentId(Long parentId);
}
```
4. 在 Service 中调用 `ParentMapper` 的 `findAll()` 方法即可查询所有数据,并且带出每个 `Parent` 对象对应的 `Child` 对象的总数。
```java
@Service
public class ParentService {
@Autowired
private ParentMapper parentMapper;
public List<Parent> findAll() {
return parentMapper.findAll();
}
}
```
阅读全文
相关推荐


















