java 使用 JPA 条件连接没有关系的表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30639132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Joining tables without relation using JPA criteria
提问by Idan
I have two tables with no modeled relation:
我有两个没有建模关系的表:
Table comm
with columns:
表comm
的列:
name
date
code
Table persondesc
with columns:
表persondesc
的列:
code
description
Relationship between the two tables is many to one (many commto one persondesc):
两个表之间的关系是多对一的(many commto one persondesc):
com.code = persondesc.code
com.code = persondesc.code
These two tables are mapped with annotations but I have no relation declared.
这两个表用注释映射,但我没有声明任何关系。
What I'm trying to is to select comm
table ordered by persondesc.description
.
我想要的是选择comm
由persondesc.description
.
How can I do this JPA and Hibernate?
我该如何做这个 JPA 和 Hibernate?
回答by Neil Stockton
So if your classes have no "relation" then you do a query like
因此,如果您的课程没有“关系”,那么您可以进行类似的查询
SELECT a FROM A a, B b WHERE a.someField = b.otherField ORDER BY b.anotherField
Which can be achieved using JPA Criteria, something like
可以使用 JPA Criteria 来实现,例如
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<A> crit = cb.createQuery(A.class);
Root<A> aRoot = crit.from(A.class);
Root<B> bRoot = crit.from(B.class);
aRoot.alias("a");
bRoot.alias("b");
crit.select(aRoot);
Predicate fieldEquals = cb.equal(aRoot.get(A_.someField), bRoot.get(B_.otherField);
crit.where(fieldEquals);
crit.orderBy(cb.asc(bRoot.get(B_.anotherField)));
... Or just redesign your classes and do your developers a favour.
... 或者只是重新设计您的课程并帮您的开发人员一个忙。
回答by Maksim
In case you need to sort by column which is in another table, you can create "fake" dependency with disabled insertable and updatable attributes. Domain model would looks like this:
如果您需要按另一个表中的列排序,您可以使用禁用的可插入和可更新属性创建“假”依赖项。域模型看起来像这样:
Primary entity:
主要实体:
@Entity
public class Comm {
@Id
private Long id;
@Column(name = "name")
private String name;
@Column(name = "date")
private Date date;
@Column(name = "code")
private String code;
@OneToOne(fetch = FetchType.LAZY) // @ManyToOne is also possible
@JoinColumn(name = "code", referencedColumnName = "code", insertable = false, updatable = false)
private PersonDesc personDesc;
}
Entity with required data for sorting:
具有排序所需数据的实体:
@Entity
public class PersonDesc {
@Id
private String code;
@Column(name = "description")
private String description;
}
After you define your domain model, it possible to create criteria query:
定义域模型后,可以创建条件查询:
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<Comm> cq = cb.createQuery(Comm.class);
Root<Comm> root = cq.from(Comm.class);
Join<Comm, PersonDesc> leftJoin = root.join("personDesc", JoinType.LEFT);
cq.select(root);
cq.orderBy(cb.asc(root.get("personDesc.description")));