初始化或不初始化JPA关系映射? [英] To initialize or not initialize JPA relationship mappings?

查看:96
本文介绍了初始化或不初始化JPA关系映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一对多的JPA关联中,初始化关系为空集合被认为是最佳实践?例如。

  @Entity 
公共类Order {

@Id
私人整数ID;

//是否应该使用空数组列表初始化行项目?
@OneToMany(mappedBy =order)
List< LineItem> lineItems = new ArrayList<>();






在上面的例子中,最好定义 lineItems ,默认值为空 ArrayList 或不是?什么是优点和缺点?JPA本身并不关心集合是否被初始化。使用JPA从数据库中检索订单时,JPA将始终返回包含OrderLines非空列表的订单。



原因:因为一个订单可以有0,1或N行,并且最好使用空白,单一尺寸或N尺寸的集合建模。如果集合为空,则必须检查代码中的任何地方。例如,如果列表为null,则此简单循环将导致NullPointerException:

  for(OrderLine line:order.getLines() ){
...
}

所以最好做到这一点始终具有非空集合,即使对于实体的新创建实例也是如此。这使得生产代码创建新订单更安全,更清洁。这也使得你的单元测试,使用不是来自数据库的Order实例,更安全,更清洁。


In one to many JPA associations is it considered a best practice to initialize relationships to empty collections? For example.

@Entity
public class Order { 

   @Id
   private Integer id;

   // should the line items be initialized with an empty array list or not?
   @OneToMany(mappedBy="order")
   List<LineItem> lineItems = new ArrayList<>();

}

In the above example is it better to define lineItems with a default value of an empty ArrayList or not? What are the pros and cons?

解决方案

JPA itself doesn't care whether the collection is initialized or not. When retrieving an Order from the database with JPA, JPA will always return an Order with a non-null list of OrderLines.

Why: because an Order can have 0, 1 or N lines, and that is best modeled with an empty, one-sized or N-sized collection. If the collection was null, you would have to check for that everywhere in the code. For example, this simple loop would cause a NullPointerException if the list was null:

for (OrderLine line : order.getLines()) {
    ...
}

So it's best to make that an invariant by always having a non-null collection, even for newly created instances of the entity. That makes the production code creating new orders safer and cleaner. That also makes your unit tests, using Order instances not coming from the database, safer and cleaner.

这篇关于初始化或不初始化JPA关系映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆