Home JPAQuery join intermediate many to many table
Reply: 1

JPAQuery join intermediate many to many table

Reygok3
1#
Reygok3 Published in 2018-01-12 14:50:33Z

I'm using QueryDSL JPA, and want to do a join between two tables. I found many similar questions here already, but my case is different from all of them by one little detail. Here is a simplified version of my classes:

@Entity(name = "TABLE_A")
public class TableA {
    @Id
    @Column(name = "ID_A", nullable = false)
    private Long idA;
}


@Entity(name = "TABLE_B")
public class TableB {
    @Id
    @Column(name = "ID_B", nullable = false)
    private Long idB;
}


@Entity(name = "TABLE_C")
public class TableC {
    @Id
    @Column(name = "ID_C", nullable = false)
    private Long idC;

    @JoinColumn(name = "ID_A", referencedColumnName = "ID_A")
    @ManyToOne
    private TableA tableA;

    @JoinColumn(name = "ID_B", referencedColumnName = "ID_B")
    @ManyToOne
    private TableB tableB;
}

Now what I want to do is join Tables A, C and B, to find the Bs which are linked to A. I know this seems like a useless step between, why not add a relation from A to B directly. In my case this is needed, these are just example classes to illustrate.

I tried this:

QTbTableA tableA = QTbTableA.tableA;
QTbTableB tableC = QTbTableC.tableC;
JPAQuery query = new JPAQuery(entityManager).from(tableA);
query.leftJoin(tableA, tableC.tableA);

The join throws an Exception because tableC.tableA is not a root path, only a property. But how do I join these tables correctly then?

Thanks in advance!

Maciej Kowalski
2#
Maciej Kowalski Reply to 2018-01-12 15:10:19Z

If you want to keep your current impl, you could start from TableC and then join the other tables:

query.from(tableC)
    .innerJoin(tableC.tableA, tableA)
    .innerJoin(tableC.tableB, tableB)
    .where(tableA.idA.eq(myId)
    .list(tableB);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.29772 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO