gpt4 book ai didi

java - Spring Data MongoDB 中的 INNER JOIN 集合

转载 作者:行者123 更新时间:2023-12-05 07:10:46 24 4
gpt4 key购买 nike

如何在 Spring Mongo 中实现 INNER JOIN?

举个例子,它实际上是不正确的,我只是想展示多对多关系:

@Document(collection = "people")
public class Person {

@Id
private String id;
private String name;
private String petId;

// Getters, setters, constructors and etc.

}

@Document(collection = "pets")
public class Pet {

@Id
private String id;
private String name;
private PetType petType; // Dog, Cat etc.

// Getters, setters, constructors and etc.

}

如果我想找到所有属于 John Smith 的狗,我应该怎么做?我需要这样的查询:

SELECT
pt.*
FROM
pets AS pt INNER JOIN people AS pe ON (pt.id = pe.petId)
WHERE
pt.petType = ${input_petType}
AND pe.name = ${input_name}

这意味着我在集合Pet和集合Person中有两个条件:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.LookupOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

public interface PetRepository extends MongoRepository<Pet, String>, PetCustomRepository {

}

public interface PetCustomRepository {

List<Pet> findAllByPetTypeAndPersonName(PetType type, String personName, Pageable pageable);

}

public class PetCustomRepositoryImpl implements PetCustomRepository {

@Autowired
private MongoTemplate mongoTemplate;

@Override
public List<Pet> findAllByPetTypeAndPersonName(PetType petType, String personName, Pageable pageable) {
LookupOperation lookup = LookupOperation.newLookup()
.from("people")
.localField("_id")
.foreignField("petId")
.as("join_people");
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("petType").is(petType)),
lookup,
Aggregation.match(Criteria.where("join_people.name").is(personName)),
Aggregation.skip(pageable.getPageNumber() * pageable.getPageSize()),
Aggregation.limit(pageable.getPageSize()));
return mongoTemplate.aggregate(aggregation, Pet.class, Pet.class).getMappedResults();
}

}

findAllByPetTypeAndPersonName() 方法返回空列表。我做错了什么?

最佳答案

您的 Pageable 有问题。尝试删除它,它应该返回结果

关于java - Spring Data MongoDB 中的 INNER JOIN 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61080151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com