Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - Joining tables without relation using JPA criteria

I have two tables with no modeled relation:

Table comm with columns:

name
date
code

Table persondesc with columns:

code
description

Relationship between the two tables is many to one (many comm to one persondesc):

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.

How can I do this JPA and Hibernate?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So if your classes have no "relation", then you do a query like

SELECT a FROM A a
CROSS JOIN B b
WHERE a.someField = b.otherField
ORDER BY b.anotherField

Which can be achieved using JPA Criteria, something like

CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<A> query = cb.createQuery(A.class);
Root<A> aRoot = query.from(A.class);
Root<B> bRoot = query.from(B.class);
aRoot.alias("a");
bRoot.alias("b");

query.select(aRoot)
  .where(cb.equal(aRoot.get(A_.someField), bRoot.get(B_.otherField))
  .orderBy(cb.asc(bRoot.get(B_.anotherField)));

... Or just redesign your classes and do your developers a favour.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...