gpt4 book ai didi

java - 使用限制获取多对一关系中的数据

转载 作者:行者123 更新时间:2023-12-01 14:53:33 25 4
gpt4 key购买 nike

有两个表具有@OneToMany和@ManyToOne双向关系,如下所示:

@Entity
public class Asset {
private int id;
private int count;
@OneToMany
private Set<Dealing> dealings;
...
}

@Entity
public class Dealing {

private int id;
...
@ManyToOne
@JoinColumn(name = "customer_id", nullable = false, updatable = false)
private Customer customer;
@ManyToOne
@JoinColumn(name = "product_id", nullable = false, updatable = false)
private Product product;
@ManyToOne(cascade = CascadeType.ALL)
private Asset asset;
}

一切听起来都不错,但是当我想使用这样的限制来搜索数据时,

session.createCriteria(Asset.class).add(Restrictions.eq("dealings.customer.id", customerId)).add(Restrictions.eq("dealing.product.id", productId)).list();

在这个级别我收到此错误,

could not resolve property: dealings.customer of: com.project.foo.model.Asset

解决方案之一是改变我的策略,但我浪费了时间来找到这个,顺便说一句,我对此一无所知,你呢?

最佳答案

首先,您没有双向 OneToMany 关联,而是两个不相关的单向关联。在双向 OneToMany 关联中,必须使用 mappedBy 属性将一侧标记为多侧的反面:

@OneToMany(mappedBy = "asset")
private Set<Dealing> dealings;

其次,对此类静态查询使用条件 API 太过分了,并且会导致代码比必要的更难阅读。我会简单地使用 HQL,它更容易阅读。恕我直言,标准应该用于动态查询,但不适用于静态查询:

select asset from Asset asset 
inner join asset.dealings dealing
where dealing.customer.id = :customerId
and dealing.product.id = :productId

无论您使用 HQL 还是 Criteria,都不能使用 asset.dealings.customer,因为 asset.dealings 是一个集合。集合没有客户属性。为了能够引用 Dealing 实体的属性,您需要一个联接,如上面的 HQL 查询所示。 Criteria 也是如此:

Criteria criteria = session.createCriteria(Asset.class, "asset");
criteria.createAlias("asset.dealings", "dealing"); // that's an inner join
criteria.add(Restrictions.eq("dealing.customer.id", customerId);
criteria.add(Restrictions.eq("dealing.product.id", productId);

关于java - 使用限制获取多对一关系中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14552184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com