【发布时间】:2018-03-06 18:06:34
【问题描述】:
我正在重构我的应用程序,它使用 Hibernate(使用 Spring)。我有几个实体,它们在 ElementCollection 中有关联的项目。所以在它看起来像之前:
@Entity
class GroupA {
.... id, .. omitted
@ElementCollection
@OrderColumn
List<Item> items = new ArrayList<>();
}
@Entity
class GroupB {
.... id, .. omitted
@ElementCollection
@OrderColumn
List<Item> items = new ArrayList<>();
}
这些组也包含在列表中的另一个实体中。我在我的服务中使用@Transactional,我在其中请求实体,并在需要时使用Hibernate.initialize(method)(在我的服务内)加载孩子。
当我重构为项目可以扩展的基类时,例如:
@MappedSuperClass
public class BaseItem {
@Id
@GenereratedValue
private Integer id;
@ElementCollection
@OrderColumn
List<Item> items = new ArrayList<>();
}
当我运行它时,我收到一个错误Failed to lazy initialize collection。我可以通过将fetch=EAGER 添加到我的元素集合来解决它。
我做错了吗?我希望在使用 @MappedSuperClass
更新 1 一个非常关键的部分,我忘了提到,我正在使用 Hibernate Envers 来审核我的组
更新 2:我的服务代码:
@Service
@Transactional
public class ProductService{
private ProductRepository repository;
public ProductService(ProductRepository repository) {
this.repository = repository;
}
public Product findOne(Integer id) {
Product one = repository.findOne(id);
Hibernate.initialize(one.getAGroups());
Hibernate.initialize(one.getBGroups());
return one;
}
}
为了完整起见,我的产品实体:
@Entity
@Audited
@Getter
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Version
private Integer version;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Set<GroupA> aGroups = new HashSet<>();
@OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Set<GroupB> bGroups = new HashSet<>();
}
【问题讨论】:
-
您描述的错误听起来像是取决于您的服务。能贴出使用映射类的服务代码吗?
-
@Yserbius 感谢您的回复。我已经更新了我的帖子。
-
可以添加异常堆栈跟踪吗?