Persisting collection where members are subclasses


OK, I have a number of classes which are all subclasses of Entry (e.g., Folder, Link, Book). In the Folder class, there is a @OneToMany Map<String, Entry> children

If I store something in that map which is an Entry, then I can persist just fine. But if I try to put any of the subclasses into the map, then I get 

[ObjectDB 2.3.6] javax.persistence.RollbackException
Failed to commit transaction: Attempt to persist a reference to a non managed instance - field (error 613)

is this a bug in ObjectDB or should I be handling this differently? Would this work better using JDO rather than JPA?



Polymorphism is supported by ObjectDB, and you shouldn't have any problem in persisting a map with different value types.

The error message may indicate that the map values include entity objects that have not been persisted. You have to persist every entity object explicitly unless cascading persist is enabled (it is enabled by default in JDO, but that is the only difference between JPA and JDO in this context).

If you still cannot make it work  - post a test case.

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)

I've attached my key classes. 

Here's the test case which is failing:

public void canRetrieveFolderByName() {
  Folder f = new Folder("A");
  f.addChild(new Folder("B"), "B");
  f.addChild(new Folder("C"), "C");

  List<Entry> savedEntries = entryDao.findAll();
  List<Folder> loadedFolders = entryDao.findFolderByName("B");
  Assert.assertEquals(1, loadedFolders.size());
  Assert.assertEquals(f, loadedFolders.get(0));

The following test seems to work fine:

import java.util.*;

import javax.persistence.*;

public class T728 {

    public static void main(String[] args) {
        EntityManagerFactory emf =
        EntityManager em = emf.createEntityManager();

        Folder f = new Folder("A");
        f.addChild(new Folder("B"), "B");
        f.addChild(new Folder("C"), "C");

    public static class Entry {
    public static class Folder extends Entry {
        String name;
        private Map<String,Entry> children = new HashMap<String,Entry>();

        Folder(String name) {
  = name;

        public void addChild(Folder folder, String key) {
            children.put(key, folder);

Try to change it to demonstrate the problem. Unfortunately very little can be done with a non runnable test as the one that you have published at #3.

ObjectDB Support
ObjectDB - Fast Object Database for Java (JPA/JDO)

Post Reply

To post a reply and/or subscribe to update notifications - please login