带有ElementCollection的Hibernate @MappedSuperClass

时间:2018-03-06 18:06:35

标签: java spring hibernate

我正在重构我使用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<>();
}

1 个答案:

答案 0 :(得分:0)

您的问题在调用one.getAGroups()时看起来像是在初始化时加载组中的所有项目时,哪种类型会导致延迟加载的目的。删除该代码或使用预先加载。

相关问题