我有以下实体
@Entity
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
@Basic
private String title;
@Basic
private double price;
@Basic
private String description;
private Map<String, Integer> map;
}
然后我尝试使用 EntityManager 保存一些此类对象
EntityManager em = EMF.get().createEntityManager();
for (int i = 0; i < 10; i++) {
Product p = new Product();
//call setters
em.persist(p);
}
em.close();
但是当调用 EM 的时候就很接近
java.lang.IllegalArgumentException: operating on too many entity groups in a single transaction.
问题是为什么使用单个实体组(我认为是“产品”)进行操作会发生这种异常?
谢谢。
最佳答案
所有产品
都不在同一个实体组中。使用 JPA,Product
将是您的实体种类。
JDO 和 JPA 隐藏底层数据存储结构,该结构是分层的,就像您的操作系统目录一样。
将实体组视为数据树,其中根实体就是树根。为了提供一个清晰的示例,我将向 Product 添加一个 ProductDetail
子实体。假设每个产品都有许多产品详细信息:
/** Root entity */
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
// ...
/** Children entities */
@OneToMany
private List<ProductDetail> details;
}
@Entity
public class ProductDetail {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
}
您的数据将转换为以下分层“架构”:
Product(id=1)
|__ProductDetail(id=2)
|__ProductDetail(id=3)
|__ProductDetail(id=7)
Product(id=4)
|__ProductDetail(id=5)
|__ProductDetail(id=6)
...
如您所见,如果您的 Product
实体不共享公共(public)父实体(例如,其他某个类持有对产品的 @OneToMany
引用),则它们中的每个实体被视为根实体,这意味着每个产品都位于其自己的实体组中。
现在是什么docs说说实体组上的交易:
(使用 JPA,“正常”事务和 XG 事务之间的区别由框架处理)
All Datastore operations in a transaction must operate on entities in the same entity group if the transaction is a single group transaction, or on entities in a maximum of five entity groups if the transaction is a cross-group (XG) transaction.
这就是为什么在单个数据存储事务中创建 10 个新的 Product
(根)实体无疑会失败。
另一方面,使用上面的示例,您可以在同一事务中创建 20 个 ProductDetail
实体(如果它们属于同一 Product
实体)。 (您也可以同时更新产品)
关于java - 无法保存一组非常简单的实体,因为检测到 XG 事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111137/