簡體   English   中英

在AdditionalCriteria中使用一對多關系

[英]Using one to many relation in AdditionalCriteria

實體:帖子,空間和個人資料。 綜上所述:

class Post { Space space; String text; }

class Space { List<Profile> members; }

class Profile { String username; List<Space> spaces; }

如何在Post上設置@AdditionalCriteria以僅返回屬於當前用戶所屬空間的帖子。

到目前為止,我已經嘗試過以下內容。

#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類型。使用顯式值為Types的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 =(子選擇)

@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。

通過使用不太優雅的解決方案解決了它:

首先,我向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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM