问题
In a spring boot + JPA applition, I have a user table and a item table with a ManyToMany relationship. The users can "follow" any Item element, in a twitter/facebook style to get the posts related to that item, get notificacions when an item change, etc.
The classes are like this, very simple way:
UserEntity.java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Size(max = 50)
@Column(name = "username", length = 50)
private String username;
@ManyToMany
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JoinTable(name = "user_follow_item",
joinColumns = @JoinColumn(name="user_id", referencedColumnName="id"),
inverseJoinColumns = @JoinColumn(name="follow_item_id", referencedColumnName="id"))
private Set<Items> followItems = new HashSet<>();
ItemEntity.java
@ManyToMany(mappedBy = "followItems")
private Set<User> followUsers = new HashSet<>();
The query is made with JpaRepository repository classes and exposed in spring boot throught a @RestController class and all works just fine.
The question is, in a query looking for items by id, it is possible to get if the current user (the logged user) is following the item? All the data in one single query. With this query I get the item info, but I don't know how to get if the user if following the item:
@Query("select item from Item item left join item.followUsers userFollow on userFollow.login = ?#{principal.username} where item.id = :id ")
Item itemWithCurrentUserFollows(@Param("id") Long id);
The query in native SQL is something like this (when i get data in "follow" part I know that the user is following the item) but I don't know how to realice this in a JPA query:
SELECT * FROM item left join (user user join user_follow_item follow) on user.id = follow.user_id and follow.follow_item_id = item.id and user.username = 'mockUser' where item.id = 1;
Any ideas are welcome (@Formula, a extra boolean value with this info, etc...)
Many Thanks!
来源:https://stackoverflow.com/questions/48947756/get-if-a-user-is-following-element-in-a-query-with-jpa-hibernate