我有一个 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 oforg.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 callingpersist()
for example, Hibernate will actually replace theHashSet
with an instance of Hibernate's own implementation ofSet
.
如果让它 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?
- 我 不会在 getter 中执行赋值。
- 如果此时集合应该为
null
,就让它为null
。
- 如果此时集合应该为
- 我看不到你们服务的附加值
- 为什么不直接调用
foo.getBars()
? - 为什么要转换集合?
- 为什么不直接调用
关于java - 在 Spring-Hibernate 项目中初始化实体集合 (POJO) 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4050259/