我希望能够在hql中获得两个用户的共同朋友。 有没有办法用h2 db做到这一点。 我正在使用带有h2嵌入式数据库的spring-boot 1.5.6。 以下是我的用户实体。
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@Version
@Column(name="version")
private int version;
@NotNull
@Column(name="username", nullable=false, unique=true)
private String username;
@Column(name="email", nullable=false, unique=true)
private String email;
@Column(name="password", nullable=false)
private String password;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "friends")
private Set<User> friends;
和存储库
public interface UserRepository extends PagingAndSortingRepository<User, Long>{
User findByEmailAndPassword(String email, String password);
这是我最近的尝试,出于某种原因让我出现例外情况。
@Query("Select friends from User U join U.friends friends where size (friends.username) > 1 and exists (select friends from User U1 join U1.friends friends1 where friends1.username = ?1) and exists (select friends from User U2 join U2.friends friends2 where friends2.username = ?2)")
List<User> findMutualFriends(String username, String friend);
当我尝试从中获取重复值时,我得到了异常。即使我正在使用他们加入,也无法访问用户名的朋友。这是堆栈跟踪:
Caused by: org.h2.jdbc.JdbcSQLException: Column "USER2_.USER_ID" not found; SQL statement:
select user2_.id as id1_4_, user2_.acc_status as acc_stat2_4_, user2_.email as email3_4_, user2_.gender as gender4_4_, user2_.password as password5_4_, user2_.username as username6_4_, user2_.version as version7_4_ from user user0_ inner join friends friends1_ on user0_.id=friends1_.user_id inner join user user2_ on friends1_.friends_id=user2_.id where (select count(user2_.user_id) from friends friends1_, user user2_ where user0_.id=friends1_.user_id and friends1_.friends_id=user2_.id)>1 and (exists (select user2_.id as id1_4_ from user user3_ inner join friends friends4_ on user3_.id=friends4_.user_id inner join user user5_ on friends4_.friends_id=user5_.id where user5_.username=?)) and (exists (select user2_.id as id1_4_ from user user6_ inner join friends friends7_ on user6_.id=friends7_.user_id inner join user user8_ on friends7_.friends_id=user8_.id where user8_.username=?)) [42122-196]
任何想法如何做到导致我找不到答案。也许它可以做得更容易,但我是hql的新手,无法弄明白。
感谢。