为什么包含关键字 IN return 的查询总是一个空列表?
Why does a query contained keyword IN return always an empty list?
有一个实体:
@Entity
class User {
@Id
private Long id;
...
@NotEmpty
@CollectionElement
private List<String> IPs;
// setters and getters
}
数据库中的 table 用户:
ID | ...
-----
1 | ...
=====
数据库中的tableUSER_IPS:
USER_ID | IPS
-----
1 | '127.0.0.1'
=====
存储库是:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u "
+ "WHERE :request IN u.IPs")
List<User> getUsers(@Param("requestIP") String iP);
}
当使用“127.0.0.1”作为参数调用存储库方法时,它 return 始终是一个空列表,而它必须 return 一个 id = 1 的用户数据库中恢复的数据。
有什么问题?
您可以使用 IN ELEMENTS 或 MEMBER OF
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u "
+ "WHERE :request IN ELEMENTS(u.IPs)")
List<User> getUsers(@Param("requestIP") String iP);
}
或:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u "
+ "WHERE :request MEMBER OF u.IPs")
List<User> getUsers(@Param("requestIP") String iP);
}
有一个实体:
@Entity
class User {
@Id
private Long id;
...
@NotEmpty
@CollectionElement
private List<String> IPs;
// setters and getters
}
数据库中的 table 用户:
ID | ...
-----
1 | ...
=====
数据库中的tableUSER_IPS:
USER_ID | IPS
-----
1 | '127.0.0.1'
=====
存储库是:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u "
+ "WHERE :request IN u.IPs")
List<User> getUsers(@Param("requestIP") String iP);
}
当使用“127.0.0.1”作为参数调用存储库方法时,它 return 始终是一个空列表,而它必须 return 一个 id = 1 的用户数据库中恢复的数据。
有什么问题?
您可以使用 IN ELEMENTS 或 MEMBER OF
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u "
+ "WHERE :request IN ELEMENTS(u.IPs)")
List<User> getUsers(@Param("requestIP") String iP);
}
或:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u "
+ "WHERE :request MEMBER OF u.IPs")
List<User> getUsers(@Param("requestIP") String iP);
}