我有一个 SQL 表:
@Table(name = "population_table")
public class Population {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String country;
private String state;
private String area;
private String population;
}
Run Code Online (Sandbox Code Playgroud)
我想获得一个计数,按国家和州分组,输出类为计数列表:
private static class Count {
private String country;
private String state;
private long count;
}
Run Code Online (Sandbox Code Playgroud)
我知道查询是
SELECT country, state, Count(*)
FROM population_table
GROUP BY country, state
Run Code Online (Sandbox Code Playgroud)
但我想使用 JPA 规范来做到这一点。如何在 Spring Boot 中使用 JPA 规范来实现这一目标?
我有一个 mongodb,它存储具有以下键的集合:parentId、childId 及其自己的 ID(“_id”)。
当我使用 Spring Query 查询数据库时,我只想获取“_id”值,而不是满足查询的整个数据。
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
@Autowired
private MongoTemplate mongoTemplate;
Query query = new Query(Criteria.where("parentId").is(id1).and("childId").is(id2));
List<MyClass> child = mongoTemplate.find(query, MyClass.class);
List<String> currentId = new ArrayList<>;
for (int i = 0; i < child.size(); i++) {
currentId.add(child.get(i).getId());
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了满足查询的对象列表。然后,我迭代这些对象并获取 ID,但我只想通过查询本身从这些对象中获取“_id”值。