6
votes

This question is related to Spring Data MongoDB model classes without annotations.

I have a situation where I need to store my domain classes either in RDBMS store or NoSQL store. Say for example my domain classes are User, Feature, PaymentRequest, Order, OrderLine, OrderHeader etc.

I cannot use any annotation on my domain classes for various reasons.

Application team will specify in which persistent store they like to store. They might configure to store it in MongoDB or in MySQL or in Oracle etc.

My requirement is when I am storing in MongoDB say using spring-data-mongodb I want to leverage the DBRefs for associated objects in my domain object.

How can I achieve with spring-data-mongodb without using annotations in my model classes.

class Role 
{

    String id;
    String roleName;

}

class User {

    String id;
    String firstName;
    String lastName;

    List<Role> userRoles;
}

When I save User object I want to ensure that in MongoDB Role objects are stored as DBRefs instead of actual Role object graph.

My question is ─ without using annotations in my User and Role classes ─ how can I achieve this?

I searched the user's forums and could not find a way. That's why I'm posting my question here.

Thanks, Kishore Veleti A.V.K.

1

1 Answers

0
votes

Not sure if you ever figured this out, but you can use AspectJ to create an ITD (inter-type declaration) to weave in the annotations into the class without having to actually modify the original code.

For example, to turn your userRoles into a DBRef, you just need this aspect:

import org.springframework.data.mongodb.core.mapping.DBRef;
privileged aspect User_Mongo {   
    declare @field: * User.userRoles : @DBRef;
}

This simply adds the @DBRef annotation to any fields within User named userRoles. You can look at the AspectJ documentation for more information on field patterns and ITDs.