我正在使用for循环在验证时迭代持久化表单对象,然后与非持久化表单对象进行比较。我在循环中使用.contains,但是第一个循环返回true,并且每个其他循环都返回false,即使pr对象不包含prPersist对象。有人能告诉我我做错了什么,或者是否有更好的方法来解决这个问题?感谢
Hibernate Entity
PurchaseRequest对象
@OneToMany(mappedBy = "purchaseRequest", cascade=CascadeType.ALL, orphanRemoval=true)
public List<LineItem> getLineItems() {
if(lineItems == null ){
lineItems = new ArrayList<LineItem>();
}
return lineItems;
}
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
LineItem对象
@ManyToOne
@JoinColumn(name = "pr_id", nullable = false)
private PurchaseRequest purchaseRequest;
public PurchaseRequest getPurchaseRequest() {
return purchaseRequest;
}
public void setPurchaseRequest(PurchaseRequest purchaseRequest) {
this.purchaseRequest = purchaseRequest;
}
Page Class
private List<LineItem> lineItems;
private PurchaseRequest pr;
@Persist
private PurchaseRequest prPersist;
System.out.println("prPersist size " + prPersist != null ? prPersist.getLineItems().size() : "");
System.out.println("pr size outer loop " + pr.getLineItems().size());
if(prPersist != null) {
for(LineItem _lineItem : prPersist.getLineItems()) {
System.out.println("pr lineItem object value " + _lineItem.getQuantity());
System.out.println("pr lineItem size inner loop " + pr.getLineItems().size());
System.out.println("pr lineItem contains prPersist lineItem " + pr.getLineItems().contains(_lineItem));
if(!pr.getLineItems().contains(_lineItem)) {
_lineItem.setPurchaseRequest(pr);
pr.getLineItems().add(_lineItem);
System.out.println("new line item added");
}
}
prPersist = null;
}
打印输出结果
prPersist size 2
pr size outer loop 0
pr lineItem object value 4
pr lineItem size inner loop 0
pr lineItem contains prPersist lineItem false
new line item added
pr lineItem object value 5
pr lineItem size inner loop 1
pr lineItem contains prPersist lineItem true
设置prPersist
void onValidate() {
prPersist = null;
if (form.getHasErrors()) {
prPersist = pr;
}
}
答案 0 :(得分:1)
鉴于prPersist
和'pr'是不同的实例,我猜测每个包含的LineItem
可以是不同的实例吗?
如果是这样,我猜您在equals
上实施LineItem
方法时遇到了问题。
答案 1 :(得分:0)
似乎没有足够的信息继续下去。尝试在contains()之前打印pr.getLineItems()
和_lineItem
的内容。
答案 2 :(得分:0)
我可以通过用以下代码替换它来简化包含条件。
if(prPersist != null) {
for(LineItem _lineItem : prPersist.getLineItems()) {
if(_lineItem.getId() == null) {
_lineItem.setPurchaseRequest(pr);
pr.getLineItems().add(_lineItem);
}
}
prPersist = null;
}