实体:帖子,空间和个人资料。总结:
class Post { Space space; String text; }
class Space { List<Profile> members; }
class Profile { String username; List<Space> spaces; }
如何在@AdditionalCriteria
上设置Post
仅返回属于当前用户所属空间的帖子。
到目前为止我所尝试的内容如下。
#1 - :space.members中的currentUserProfile
@AdditionalCriteria(":currentUserProfile in (this.space.members)")
Profile profile = new Profile();
em.setProperty("currentUserProfile", profile);
结果:
Exception [EclipseLink-6015] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.QueryException
Exception Description: Invalid query key [space] in expression.
Query: ReadObjectQuery(name="readPost" referenceClass=Post )
#2 - :space.members的currentUserProfile成员
@AdditionalCriteria(":currentUserProfile member of this.space.members")
Profile profile = new Profile();
em.setProperty("currentUserProfile", profile);
结果:
Caused by: org.postgresql.util.PSQLException: Não pode inferir um tipo SQL a ser usado para uma instância de br.com.senior.social.model.profile.Profile. Use setObject() com um valor de Types explícito para especificar o tipo a ser usado.
at org.postgresql.jdbc.PgPreparedStatement.setObject(PgPreparedStatement.java:1039)
英文:“无法推断用于_的实例的SQL类型。使用带有显式值的类型的setObject()来设置要使用的类型。”
#3 - profile.spaces中的this.space
@AdditionalCriteria("this.space in (select p.spaces from Profile p where p.username = :currentUsername)")
String username = "foo";
em.setProperty("currentUsername", username);
结果:
Exception [EclipseLink-0] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [this.space in (select p.spaces from Profile p where p.username = :currentUsername)].
[131, 139] The state field path 'p.spaces' cannot be resolved to a collection type.
#4 - :currentUsername =(subselect)
@AdditionalCriteria(":currentUsername = (select p.username from Profile p where p.username = :currentUsername and this.space in (p.spaces))")
String currentUsername = "foo";
em.setProperty("currentUsername", currentUsername);
结果:
org.postgresql.util.PSQLException: ERROR: relation "post" does not exist
Posição: 423
EclipseLink在不使用描述符(前缀)的情况下为表发出SQL。
答案 0 :(得分:0)
使用不那么优雅的解决方案来解决它:
首先,我在Post-Space关系中添加了一个原始ID属性:
class Post {
@Column(name = "SPACE_ID", updatable = false, insertable = false)
private String spaceId;
}
然后在附加标准中引用它:
@AdditionalCriteria("this.spaceId in :currentUserSpaceIds")
并将:currentUserSpaceIds
初始化为当前用户所属的实际空格。
EntityManager em = ...;
Profile profile = ...; // current user profile
List<Space> spaces = profile.getSpaces();
List<String> spaceIds = new ArrayList<>();
for (Space space : spaces) { spaceIds.add(space.getId()); }
em.setProperty("currentUserSpaceIds", spaceIds);