Spring Data에서 클래스에 대한 MongoDb 컬렉션 이름을 구성하는 방법
라는 컬렉션이 있습니다.Products인터페이스로 표시되는 내 MongoDB 데이터베이스에서IProductPrice내 자바 코드로.다음 리포지토리 선언으로 인해 SpringDate가 컬렉션을 찾습니다.db.collection: Intelliprice.iProductPrice.
나는 그것이 그것을 조사하도록 구성하기를 원합니다.db.collection: Intelliprice.Products외부 구성을 사용하는 것이 아니라@Collection(..)에 대한 주석.IProductPrice이것이 가능합니까?어떻게 해야 하나요?
public interface ProductsRepository extends
MongoRepository<IProductPrice, String> {
}
현재 이를 달성할 수 있는 유일한 방법은 도메인 클래스에 다음과 같이 주석을 다는 것입니다.@Document사용collection이 클래스의 컬렉션 인스턴스의 이름을 정의하는 속성을 유지해야 합니다.
그러나 클래스, 컬렉션 및 속성 이름을 보다 글로벌한 방식으로 처리하는 방법을 구성하기 위해 플러그인 가능한 이름 지정 전략을 추가할 것을 제안하는 JIRA 문제가 있습니다.사용 사례에 대해 자유롭게 의견을 제시하고 투표해 주십시오.
위의 Oliver Gierke의 답변을 사용하여 한 엔티티에 대해 여러 컬렉션을 만들어야 하는 프로젝트를 수행하면서 스프링 리포지토리를 사용하고 싶었고 리포지토리를 사용하기 전에 사용할 엔티티를 지정해야 했습니다.
요청 시 SPeL을 사용하여 저장소 컬렉션 이름을 수정할 수 있었습니다.한 번에 하나의 컬렉션만 작업할 수 있습니다.
도메인 개체
@Document(collection = "#{personRepository.getCollectionName()}")
public class Person{}
기본 Spring 저장소:
public interface PersonRepository
extends MongoRepository<Person, String>, PersonRepositoryCustom{
}
사용자 지정 리포지토리 인터페이스:
public interface PersonRepositoryCustom {
String getCollectionName();
void setCollectionName(String collectionName);
}
구현:
public class PersonRepositoryImpl implements PersonRepositoryCustom {
private static String collectionName = "Person";
@Override
public String getCollectionName() {
return collectionName;
}
@Override
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
}
사용 방법:
@Autowired
PersonRepository personRepository;
public void testRetrievePeopleFrom2SeparateCollectionsWithSpringRepo(){
List<Person> people = new ArrayList<>();
personRepository.setCollectionName("collectionA");
people.addAll(personRepository.findAll());
personDocumentRepository.setCollectionName("collectionB");
people.addAll(personRepository.findAll());
Assert.assertEquals(4, people.size());
}
그렇지 않으면 구성 변수를 사용해야 하는 경우 다음과 같은 소스를 사용할 수 있습니다.
@Value("#{systemProperties['pop3.port'] ?: 25}")
조금 늦었지만, 애플리케이션 구성에 직접 액세스하는 스프링 부트에서 몽고 컬렉션 이름을 동적으로 설정할 수 있다는 것을 알게 되었습니다.
@Document(collection = "#{@environment.getProperty('configuration.property.key')}")
public class DomainModel {...}
이러한 방식으로 주석 속성을 설정할 수 있습니다.
제가 추가할 수 있는 유일한 의견은 콩 이름에 @ 접두사를 추가해야 한다는 것입니다.
collection = "#{@beanName.method()}"
콩 공장에서 콩을 주입하는 경우:
@Document(collection = "#{@configRepositoryCustom.getCollectionName()}")
public class Config {
}
전 그걸 알아내려고 애썼어요
전체 예:
@Document(collection = "#{@configRepositoryCustom.getCollectionName()}")
public class Config implements Serializable {
@Id
private String uuid;
private String profile;
private String domain;
private String label;
private Map<String, Object> data;
// get/set
}
public interface ConfigRepositoryCustom {
String getCollectionName();
void setCollectionName(String collectionName);
}
@Component("configRepositoryCustom")
public class ConfigRepositoryCustomImpl implements ConfigRepositoryCustom {
private static String collectionName = "config";
@Override
public String getCollectionName() {
return collectionName;
}
@Override
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
}
@Repository("configurations")
public interface ConfigurationRepository extends MongoRepository<Config, String>, ConfigRepositoryCustom {
public Optional<Config> findOneByUuid(String Uuid);
public Optional<Config> findOneByProfileAndDomain(String profile, String domain);
}
serviceImple에서의 사용:
@Service
public class ConfigrationServiceImpl implements ConfigrationService {
@Autowired
private ConfigRepositoryCustom configRepositoryCustom;
@Override
public Config create(Config configuration) {
configRepositoryCustom.setCollectionName( configuration.getDomain() ); // set the collection name that comes in my example in class member 'domain'
Config configDB = configurationRepository.save(configuration);
return configDB;
}
SpEL에서는 정적 클래스와 메서드를 사용합니다.
public class CollectionNameHolder {
private static final ThreadLocal<String> collectionNameThreadLocal = new ThreadLocal<>();
public static String get(){
String collectionName = collectionNameThreadLocal.get();
if(collectionName == null){
collectionName = DataCenterApiConstant.APP_WECHAT_DOCTOR_PATIENT_COLLECTION_NAME;
collectionNameThreadLocal.set(collectionName);
}
return collectionName;
}
public static void set(String collectionName){
collectionNameThreadLocal.set(collectionName);
}
public static void reset(){
collectionNameThreadLocal.remove();
}
}
엔티티 클래스에서 @Document(수집 = "#{T(com.test.data).CollectionNameHolder).get()}")"
그 다음에, 을 사용합니다.
CollectionNameHolder.set("testx_"+pageNum)
서비스 중, 및
CollectionNameHolder.reset();
도움이 되길 바랍니다.
언급URL : https://stackoverflow.com/questions/12274019/how-to-configure-mongodb-collection-name-for-a-class-in-spring-data
'programing' 카테고리의 다른 글
| 날짜로부터 연도 추출 (0) | 2023.07.08 |
|---|---|
| Excel 피벗 테이블에서 쿼티일을 사용하여 하위 모집단별로 데이터 요약 (0) | 2023.07.08 |
| Spring boot WebClient를 사용하여 페이지화된 API 응답을 수집하는 방법은 무엇입니까? (0) | 2023.07.08 |
| Python - 상수 목록 또는 사전을 정의하는 최상의/최소한의 방법 (0) | 2023.07.03 |
| 유형 스크립트 클래스: "오버로드 서명이 함수 구현과 호환되지 않습니다." (0) | 2023.07.03 |