Announcement Announcement Module
No announcement yet.
Polymorphism for spring data? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Polymorphism for spring data?

    Does spring-data support polymorphism? For example, can persist a concrete implementation using a repository declared to manage the interface?

    public interface Artifact 
       ObjectId getId();   
       String getArtifactName();
       String getArtifactType();
       List<String> getSupportedModels();
       Date getDateAdded(); 
       File getArtifactFile();
    public abstract class AbstractArtifact implements Artifact
    public class ConcreteArtifact extends AbstractArtifact 
    public interface ArtifactRepository extends MongoRepository<Artifact,ObjectId> {}

    I seem to be able to instantiate a ConcreteArtifact and save it fine. The mongo shell depicts all attributes using find(). However, when I attempt to use the findOne() method on the ArtifactRepository I receive the following error:

    Code: Could not instantiate bean class []: Specified class is an interface at at at at$ReadDbObjectCallback.doWith( at at at at at at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
     sun.reflect.NativeMethodAccessorImpl.invoke( at sun.reflect.DelegatingMethodAccessorImpl.invoke( at java.lang.reflect.Method.invoke( at$QueryExecuterMethodInterceptor.executeMethodOn( at$QueryExecuterMethodInterceptor.invoke( at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed( at
     org.springframework.aop.framework.JdkDynamicAopProxy.invoke( at $Proxy123.findOne(Unknown Source) at at

  • #2
    Have you tried to pass the Class object of the concrete implementation as fondOne() argument as it is in the documentation?

    .findOne(new Query(Criteria.where("name").is("Joe")), Person.class)


    • #3
      Well...I'm pretty sure that will work. What I really want is to place different concrete implementations into the same collection and be able to query them. For example, if ConcreteA and ConcreteB are both persisted into the same collection, then I want to be able to query for all objects in the collection and know that each is materialized appropriately.

      In sum, I want to be able to save a discriminator (maybe the @Document type?) along with the object and have the Repository use that information to instantiate the correct implementation upon query.


      • #4
        Currently we unfortunately don't. As Matthias has pointed out you can be specific on the class you're querying for on the template level (and thus map data to various classes by just piping in a different type). Currently the repositories uses the domain type you type the repo to (Account in your case) to map the returned data to it. That's the only way it works right now as we do not transparently store concrete type information for root documents (we already do for nested ones). Unfortunately there won't be no general solution as on storing at the template you simply pipe in an object and we don't know you might use it behind an interface.

        However, we could let the repository save infrastructure store the concrete type in the document in case the repository is managing an interface or an abstract class. Could you please open a JIRA for that and assign it to the repository component. I will have a look at it ASAP then.



        • #5
          Thanks for the information Oliver. I will open a JIRA ticket today.

          Given this information, it would seem that a good rule of thumb for spring data would be a single domain class per collection. I had also thought that I might be able to query "across" collections as a workaround, but don't see that type of functionality either.


          • #6
            We already do entity-per-collection. Or to be more precise, one collection for the entity the repository is typed to. I think this makes much sense as document databases work quite nicely with slightly differently shaped data. Plus we can do polymorphic queries quite easily.


            • #7
              Not sure what you mean by "polymorphic" queries in the last response. Isn't that what we're suggesting should be implemented by the new JIRA issue?

              JIRA issue for this thread:



              • #8
                Polymorphic in that context means that you potentially get back objects of different types. Mostly they are in some kind of type hierarchy. If every concrete type would get it's own collection then we'd have to query the collections separately which is not only slow but also rather tricky to handle when using pagination and the like.


                • #9
                  Im using spring-data-mongodb.1.0.0.M2. Ive defined my mongorepository as

                  public interface UserRepository extends MongoRepository<User,String>{

                  And then make hte following call.

                  List<User> allUsers = userRepository.findAll();
                  I'm getting the following error.

                  org.springframework.beans.BeanInstantiationExcepti on: Could not instantiate bean class [java.util.List]: Specified class is an interface
                  at org.springframework.beans.BeanUtils.instantiateCla ss(
                  at a:346)
                  at SimpleMongoConverter.readMap(SimpleMongoConverter. java:456)
                  at SimpleMongoConverter.readCompoundValue(SimpleMongo
                  at a:361)
                  at plate$ReadDbObjectCallback.doWith(MongoTemplate.ja va:1480)
                  at plate.executeEach(
                  at plate.doFind(
                  at plate.find(
                  at ry.SimpleMongoRepository.findAll(SimpleMongoReposi
                  at ry.SimpleMongoRepository.findAll(SimpleMongoReposi
                  at ry.SimpleMongoRepository.findAll(SimpleMongoReposi
                  at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
                  at sun.reflect.NativeMethodAccessorImpl.invoke(Native
                  at sun.reflect.DelegatingMethodAccessorImpl.invoke(De
                  at java.lang.reflect.Method.invoke(
                  at toryFactorySupport$QueryExecuterMethodInterceptor. executeMethodOn(
                  at toryFactorySupport$QueryExecuterMethodInterceptor. invoke(
                  at org.springframework.aop.framework.ReflectiveMethod Invocation.proceed( :172)
                  at org.springframework.aop.framework.JdkDynamicAopPro xy.invoke(


                  What is wrong here?

                  Thanks in advance.


                  • #10
                    1. Why are you adding a @Transactional Annotation? MongoDB does not support Transactions.
                    Only Atomic Operations are supported. See

                    2. You are still using SimpleMongoConverter, which is Deprecated!

                    <mongo:mapping-converter id="converter" />

                    and <constructor-arg ref="converter" />

                    to the MongoTemplate constructor arguments

                    to your beans.xml to use the MappingMongoConverter (or instanceiate it by using the bean tag)


                    • #11
                      That worked. Thank you.


                      • #12
                        Is support for interfaces as a domain type going to be extended to find methods?

                        In the attached zipped example I have declared a finder:

                        public interface PersonRepository extends PagingAndSortingRepository<Person, String> {

                        List<Person> findByLastName( String lastName );

                        This causes template instantiation to fail with the below:

                        Caused by: java.lang.IllegalArgumentException: No property last found for type interface org.acme.Person
                        at roperty.<init>(
                        at roperty.<init>(
                        at roperty.create(
                        at roperty.create(
                        at roperty.create(
                        at roperty.from(
                        at roperty.from(
                        at art.<init>(
                        at artTree$OrPart.<init>(
                        at artTree.buildTree(
                        at artTree.<init>(
                        at ry.PartTreeMongoQuery.<init>(PartTreeMongoQuery.ja va:42)

                        Debugging it appears when Spring MongoDB attempts to "bind" using reflection it uses reflectionUtils.findField() which will calls Class.getDeclaredFields(). Put another way it just looks at fields and does not look at getters and setters which is all the interface has. Could it be changed to be able to bing to getters/setters, or alternatively bind later when it gets the concrete class?

                        Last question - any target release date for DATADOC-131 ?




                        • #13
                          Commented on the ticket. In short: that's exactly what the ticket is all about. The ticket is scheduled for 1.1-M1. As we're just on the road to 1.0-RC1 and GA so it will probably take a while.


                          • #14
                            Matthias S,

                            Can you provide a full xml config for you comments above as its not exactly clear how to make the adjustments you are suggesting.