【问题标题】:Hibernate @MappedSuperClass with ElementCollection使用 ElementCollection 休眠 @MappedSuperClass
【发布时间】: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 感谢您的回复。我已经更新了我的帖子。
  • 可以添加异常堆栈跟踪吗?

标签: java spring hibernate


【解决方案1】:

您的问题看起来像是在调用one.getAGroups(),当您在初始化中加载组中的所有项目时,这会破坏延迟加载的目的。要么删除该代码,要么使用急切加载。

【讨论】:

  • 感谢您的回答。我不确定它是否真的回答了这个问题。问题是为什么使用 MappedSuperClass 时行为会发生变化。当实体本身包含所有字段时,它会起作用
猜你喜欢
  • 2011-06-25
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 2011-06-19
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多