Uploaded image for project: 'Spring Data MongoDB'
  1. Spring Data MongoDB
  2. DATAMONGO-1896

In case of inheritance, MongoRepository.saveAll(…) does not insert elements into the aggregate collection

    XMLWordPrintable

    Details

      Description

      Let us have a simple inheritance hierarchy:

      open class Animal
      
      class Bird(val color: String): Animal()
      

      And let us make a repository for all Animals:

      @Repository
      interface AnimalRepository: MongoRepository<Animal, String>
      

      The problem is that if we save Birds to this repository, they are saved in either the "Animals" mongo collection, or the "Birds" collection, depending on whether we use MongoRepository::save or MongoRepository::saveAll:

      @RunWith(SpringRunner::class)
      @SpringBootTest
      class DemoApplicationTests {
      
          @Autowired
          lateinit var animalRepository: AnimalRepository
      
          @Before
          fun cleanup() {
              animalRepository.deleteAll()
          }
      
          @Test
          fun testNormal() {
      
              animalRepository.save(Bird("green"))           // Saves to "Animal" collection as expected
              animalRepository.saveAll(listOf(Bird("red")))  // Saves to "Bird" collection even though it should go into the "Animal" collection
      
              val count = animalRepository.count() // Counts only the documents in the "Animal" collection
      
              assertEquals(2, count) // count == 1 
          }
      }
      

      This would not be a problem in itself, but the retreival functions always work on the more general repository ("Animal" in this case).

        Attachments

          Activity

            People

            Assignee:
            olivergierke Oliver Drotbohm
            Reporter:
            martin-drozdik Martin Drozdik
            Last updater:
            Spring Issues Spring Issues
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated:
              Resolved: