我的实体中的馆藏不会被保留,无论它是简单的收藏还是关联。
我正在使用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
和name
,缺少names
集合ParentDocument
_id
和count
被保留,但即使已创建ChildDocuments
,也会丢失对孩子的引用我做错了什么? 感谢
答案 0 :(得分:1)
Hibernate OGM在底层执行一些优化,因此命令不会立即在db上执行(通常)。
使用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.flush()
之前使用session.close()
也适用于此情况。