0

I have mongodb related code in my java application and can I switch between two collections under same db in java code ?

@JsonIgnoreProperties(ignoreUnknown = true)
@Document(collection = "collectionA")
@QueryEntity
public class RepreCase {

I want to have a different collection here instead of this say collectionB @Document(collection = "collectionA") and comeback to the same collectionA, by switching between the two collections A & B under same DB

Can I do like this ? @Document(collection = "collectionA, collectionB")

Is it achievable & How ? Thanks in advance

Santosh Ravi Teja
  • 247
  • 1
  • 7
  • 18

1 Answers1

0

This example should help

Define your entity class like

@Document(collection = "${EventDataRepository.getCollectionName()}")
public class EventData implements Serializable {

Define a custom repository interface with getter and setter methods for "collectionName"

public interface EventDataRepositoryCustom {

    String getCollectionName();

    void setCollectionName(String collectionName);
}

Provide implementation class for custom repository with "collectionName" implementation

public class EventDataRepositoryImpl implements EventDataRepositoryCustom{

    private static String collectionName = "myCollection";

    @Override
    public String getCollectionName() {
        return collectionName;
    }

    @Override
    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }
}

Add EventDataRepositoryImpl to the extends list of your repository interface in this it would look like

@Repository
public interface EventDataRepository extends MongoRepository<EventData, String>, EventDataRepositoryImpl  {
}

Now in your Service class where you are using the MongoRepository set the collection name, it would look like

@Autowired
EventDataRepository  repository ;

repository.setCollectionName("collectionName");
Avinash Gupta
  • 208
  • 5
  • 18