java - 在 Spring-Hibernate 项目中初始化实体集合 (POJO) 的正确方法是什么?

标签 java hibernate spring architecture collections

我有一个 POJO 类,比如 Foo,它有一组其他实体实例,比如 bars。 此类项目也有标准的杂项类:Foo 和 Bar 的服务和 dao。

我希望 BarService 获取与某些 Foo 关联的 Bar 实例集。现在我有以下代码,我认为它在概念上是错误的。

 
public class Foo {
    Set<Bar> bars;

    public Set<Bar> getBars() {
        if (bars == null)
            return ( bars = new HashSet() );
        return bars;
    }
}
 
public class BarServiceImpl {
    public List<Bar> getListOfBars(Foo foo) {
        return new ArrayList(foo.getBars());
    }
}

3个问题: 在哪里初始化 Foo 的 Set 比较好? 哪些特定的集合和列表更适合此类目的? 我目前的实现有哪些概念性问题,如何做得更好?

提前致谢。

最佳答案

Where it is better to initialize Foo's Set?

大多数时候,我会在声明集合时对其进行初始化,这是 Hibernate 推荐的做法。引用文档:

6.1. Persistent collections

Hibernate requires that persistent collection-valued fields be declared as an interface type. For example:

public class Product {
    private String serialNumber;
    private Set parts = new HashSet();

    public Set getParts() { return parts; }
    void setParts(Set parts) { this.parts = parts; }
    public String getSerialNumber() { return serialNumber; }
    void setSerialNumber(String sn) { serialNumber = sn; }
}

The actual interface might be java.util.Set, java.util.Collection, java.util.List, java.util.Map, java.util.SortedSet, java.util.SortedMap or anything you like ("anything you like" means you will have to write an implementation of org.hibernate.usertype.UserCollectionType.)

Notice how the instance variable was initialized with an instance of HashSet. This is the best way to initialize collection valued properties of newly instantiated (non-persistent) instances. When you make the instance persistent, by calling persist() for example, Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set.

如果让它 null 是你业务的一部分,我的建议是用(通用)链接管理方法初始化它:

public class Foo {
    ...
    private Set<Bar> bars;
    ...
    public void addBar(Bar bar) {
        if (this.bars == null) {
            this.bars = new HashSet<Bar>();
        }
        this.bars.add(bar);
    }
}

What specific Sets and Lists are better for such purposes?

这完全取决于您需要的语义。 Set 不允许重复,List 允许重复并引入位置索引。

What conceptual issues has my current implementation, and how to do better?

  1. 不会在 getter 中执行赋值。
    • 如果此时集合应该为null,就让它为null
  2. 我看不到你们服务的附加值
    • 为什么不直接调用 foo.getBars()
    • 为什么要转换集合?

关于java - 在 Spring-Hibernate 项目中初始化实体集合 (POJO) 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4050259/

相关文章:

java - 在没有用户 session 计数限制的情况下使用 sessionRegistry?

java - Spring Boot,测试主应用程序类

spring - Spring 3 中的 UrlBasedViewResolver 和 Apache Tiles2

java - 识别 Google Drive Change 类型

java - 编译器如何选择正确的重写方法

Java:从过程中读取元数据

java - 如何解决hibernate复合键异常(期望IdClass映射)?

java - 删除 <String> ArrayList-Java 的元素

java - Hibernate Search 是否可以在索引过程之前预定义查询或条件?

java - 将 sql 转换为 criteriaBuilder