简体   繁体   中英

Join Entity with table that has no entity assosiated in JPQL

I have a table that has no associated Entity. I need to write JPQL query which will filter by that table's fields. Is it possible? I know that I can do one of the following:

  1. Create an Entity for that table( but it's basically a join table, so it will look strange to create an Entity class for it)
  2. Write a native query( I don't like this approach either. If I use JPA, I must use JPQL only).
  3. Create fully functional ManyToMany mapping( I just don't need it).

Could there be another approach?

Unfortunately you cannot do that with JPQL.

You should use SQL. But a native query can also return Entities. Either if the returned values matches the entity or using @SqlResultSetMapping as described here: http://javaee.support/sample/jpa-native-sql-resultset-mapping/

If you only need to join to entities on a relationship that is not mapped JPA 2.1 is able to JOIN on any table columns.

The problem was that I did not need a real many-to-many object mapping but only collection of id's in my only entity. So I came to following solution:

@ElementCollection
@CollectionTable(
   name="user_to_feed", 
   joinColumns = @JoinColumn(name = "feed_id",referencedColumnName = "id")
)
@Column(name="user_id")
private List<Integer> userIds = new ArrayList<>();

This allows me to make following query:

select f.url from Feed f join f.userIds u where :id in u

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM