无论是简单的集合还是关联,我的实体中的集合都不会持久化。
我正在将 OGM 与 mongodb 一起使用。
对于问题的示例,请考虑以下实体:
@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 个集合Document
:ChildDocument
和ParentDocument
。
- 这些
ChildDocument
文件是正确的,因为它们只需要具有_id
和name
Document
文档也只包含_id
and ,name
缺少names
集合ParentDocument
仅在and_id
中保留,count
但即使ChildDocuments
创建了对孩子的引用也丢失了
我究竟做错了什么?
谢谢