使用带 mongodb 的 Hibernate OGM 的实体中缺少集合

Missing collections in entities using Hibernate OGM with mongodb

我的实体中的集合不会持久化,无论是简单的集合还是关联。
我在 mongodb.

中使用 OGM

有关问题的示例,请考虑以下实体:

@Entity
class Document {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Type(type = "objectid")
    String id;

    String name;

    @ElementCollection
    Set<String> names;

    Document() {
        this.names = new HashSet<>();
    }

    Document(String name) {
        this();
        this.name = name;
    }
}

@Entity
class ChildDocument {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Type(type = "objectid")
    String id;

    String name;

    ChildDocument() {}

    ChildDocument(String name) {
        this.name = name;
    }
}

class ParentDocument {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Type(type = "objectid")
    String id;

    int count;

    @OneToMany(cascade = CascadeType.ALL)
    @AssociationStorage(AssociationStorageType.IN_ENTITY)
    List<ChildDocument> kids = new LinkedList<>();
}

以下设置:

final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder()
        .applySetting(OgmProperties.ENABLED, true)
        .applySetting(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta")
        .applySetting(AvailableSettings.JTA_PLATFORM, "JBossTS")
        .applySetting(OgmProperties.DATASTORE_PROVIDER, MongoDB.DATASTORE_PROVIDER_NAME)
        .applySetting(OgmProperties.DATABASE, "testdb")
        .applySetting(OgmProperties.CREATE_DATABASE, "true");

final StandardServiceRegistry registry = registryBuilder.build();
final MetadataSources sources = new MetadataSources(registry);
sources.addAnnotatedClass(Document.class);
sources.addAnnotatedClass(ChildDocument.class);
sources.addAnnotatedClass(ParentDocument.class);

final SessionFactory sessionFactory = sources.buildMetadata().getSessionFactoryBuilder()
        .unwrap(OgmSessionFactoryBuilder.class)
        .build();

还有这个短节目:

Document document1 = new Document("one");
Document document2 = new Document("two");
document2.names.add("one.one");
document2.names.add("one.two");

ParentDocument parent = new ParentDocument();
parent.count = 2;
parent.kids.add(new ChildDocument("one"));
parent.kids.add(new ChildDocument("two"));

final Session session = sessionFactory.openSession();
session.save(document1);
session.save(document2);
session.save(parent);
session.close();

sessionFactory.close();

testdb 现在包含 3 个集合:DocumentChildDocumentParentDocument

我做错了什么?
谢谢

Hibernate OGM 在后台执行一些优化,因此命令不会立即在数据库上执行(通常)。

使用 Hibernate OGM 时,您仍应为您的操作使用事务界定:

   final Session session = sessionFactory.openSession();

   session.beginTransaction();

   session.save(document1);
   session.save(document2);
   session.save(parent);

   session.getTransaction().commit();

   session.close();

这在文档中有解释:http://docs.jboss.org/hibernate/ogm/5.0/reference/en-US/html/ch11.html#transactions

请注意,在 session.close() 之前使用 session.flush() 也适用于这种情况。