0

I am using Spring Data MongoDB to load and save some simple domain classes. As a simple example lets say I have Factory and Product

@Document
public class Factory {
    @Id String id;
    String name;
    List<Product> products;
}

@Document
public class Product {
    @Id String id;
    String name;
    Date productionDate;
}

Ok, simple enough I can now create a FactoryRepository:

public interface FactoryQueryRepository extends MongoRepository<Factory, String> {}

This repository already has basic CRUD functionality to store and load Factories together with nested products. Now lets say I want to only retrieve a set of products for a given factory.

I now have two questions:

A) Can I somehow return a list of products instead of a list of factories in the FactoryQueryRepository like so:

@Query(value = "???")
public List<Product> findProductByFactoryName(String name);

B) Lets say my factory does not only have products but also employees, customers, suppliers, you name it ... Now if need to define a few special query methods for each of these nested collections then I soon end-up with a very big FactoryQueryRepository interface. So it would actually be more appropriate to create a new ...QueryRepositoy for Product, Employee, Customer and so on. But when I try to do this, it seems it only works if I first save a stand alone Product object that is not nested inside a Factory. Is there a way that I can (similar to question A) define a ProductQueryRepository interface and use it to retrieve all Products that are nested inside a Factory by specifying some filter criteria of the Factory, something like this:

public interface ProductQueryRepository extends MongoRepository<Product, String> {
    @Query(/* select products from factory where name = '?0' */)
    public List<Product> findProductsByFactoryName(String name);
}

Shoud I in this case rather make use of the @DBRef than to use nested objects?

1 Answer 1

1

For your question A) - you should use MongoTemplate to write a custom query.

For your question B) you should try to avoid any references when using MongoDB. MongoDB only guarantees atomic writes on a single document, not across multiple documents. If you must use a reference then you should not use DBRef, you should implement the reference manually (this is mentioned explicitly in the docs http://docs.mongodb.org/manual/reference/database-references/)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.