2

I am playing around with Spring Data Rest. One thing I am not being able to accomplish is to store nested objects in dedicated repositories. Here are my two model classes Person and Address:

@Entity
public class Address {
    @NotEmpty public String  address, email;
    @Id public String id;
}

@Entity
public class Person {
    @Id public String id;
    public String firstName, lastName;
   @OneToOne public Address address;
}

And here my two Mongo repositories that I use within Spring Boot app.

@RepositoryRestResource(collectionResourceRel = "person", path = "person")
    public interface PersonRepository extends MongoRepository<Person, String> {}

 @RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends MongoRepository<Address, String> {}

Now, I make the following post request to create a person. { "firstName": "My first name", "lastName": "My last name", "id":"50e30c24-b8b7-4110-a421-687f67c077d4", "address": { "id":"8969abf3-17c5-4d7f-bc8c-16dd97808510", "address": "fgfgfg", "email": "fgfggf" } }

The person is created in the Person repository. And when I pull the person from the repository, it very well contains the address. However, the address is not stored in the address repository. Instead it is stored inline with the person.

Though if I understand the documentation correctly (see http://docs.spring.io/spring-data/rest/docs/current/reference/html/#projections-excerpts.projections) , in this case, because the Person repository is defined, the Person resource should render the address as a URI to it's corresponding resource, which I presume would be stored in a separate repository.

So, the question is how do I cause the address to be stored in a separate repository? Could it be that this doesn't work with MongoRepository as described?

1 Answer 1

3

If you are working with MongoDB specifically, don't use JPA annotations. The two magical annotations you do want are these:

@org.springframework.data.annotation.Id
@org.springframework.data.mongodb.core.mapping.DBRef

I fully qualified them above so you could see the difference between other similar annotations.

@DBRef is what tells Springs MongoDB drivers to store those objects in a separate bucket.

Here are your new classes:

public class Address {
    @NotEmpty public String  address, email;
    @Id public String id;
}

public class Person {
    @Id public String id;
    public String firstName, lastName;
    @DBRef public Address address;
}
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.