简体   繁体   English

将实体与在JPQL中没有关联的表的表连接

[英]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. 我需要编写JPQL查询,该查询将按该表的字段进行过滤。 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) 为该表创建一个Entity(但它基本上是一个联接表,因此为其创建Entity类看起来很奇怪)
  2. Write a native query( I don't like this approach either. If I use JPA, I must use JPQL only). 编写本机查询(我也不喜欢这种方法。如果使用JPA,则必须仅使用JPQL)。
  3. Create fully functional ManyToMany mapping( I just don't need it). 创建功能齐全的ManyToMany映射(我只是不需要它)。

Could there be another approach? 还有其他方法吗?

Unfortunately you cannot do that with JPQL. 不幸的是,您无法使用JPQL做到这一点。

You should use SQL. 您应该使用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/ 如果返回的值与实体匹配,或者使用@SqlResultSetMapping,如此处所述: 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. 如果只需要在未映射的关系上加入实体,则JPA 2.1可以在任何表列上进行JOIN。

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. 问题是我不需要真正的多对多对象映射,而只需要我唯一的实体中ID的集合。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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