开发者

JPQL check many-to-many relationship

Just a quick question:

There's the entity (for example User) who is connected with the ManyToMany relationship to the same entity (for example this relation describes "fr开发者_开发知识库iendship" and it is symmetric).

What is the fastest way in terms of execution time to check if User A is a "friend" of user B? The "dumb" way would be to fetch whole List and then check if user exists there but that's obviously the overhead.

I'm using JPA 2

Here's the sample code:

@Entity
@Table(name="users")
public class UserEntity {
    @ManyToMany(fetch = FetchType.LAZY)
    private List<UserEntity> friends;

    ....
}


If you don't want to retrieve the whole List, what about using a MEMBER OF? Something like this:

SELECT user FROM UserEntity user WHERE :friend MEMBER OF user.friends

That would give you all people who have B as friend. If you want to restrict the results to A only, add a condition in the WHERE clause.

Not sure it's the best way to achieve what you want though. The "dumb" approach doesn't look so dumb actually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜