2017-10-16 38 views
1

我有一个Spring数据JPA实体规划环境地政司格式化查询春季数据JPA W/Spring Security的

@Entity  
public class User { 

    private static final long serialVersionUID = 1L; 

    @Id 
    private Long id; 

,我要包括财产mutualFriends这是对查询用户principle查询的结果(在春季安全性),使用SpELEvaluationContext extension model

继规划环境地政司的例子,我想出了这样的事情:

@Formula("select count(friendship) from Friendship friendship where " + 
     "friendship.owner.id = id " + 
     "and friendship.friend in " + 
     "(SELECT f.friend FROM Friendship f where f.owner.id = " + 
     "?#{principle != null ? principal.id : id}) ") 
    private Integer mutualFriends; 

同一实体(User)时使用的身份验证用户的,所以我需要有一些逻辑,以确定是否principle是产品尚未推出或我得到一个错误:

Caused by: org.postgresql.util.PSQLException: No value specified for parameter 2.

?#{principle != null ? principal.id : id} 

这是格式正确无误?

这里是正在执行的Hibernate查询相关的部分时,我得到异常:从友谊友谊

select user0_.id as id1_19_, user0_.created_by as created_2_19_, user0_.created_date as created_3_19_, user0_.last_modified_by as last_mod4_19_, user0_.last_modified_date as last_mod5_19_, user0_.activated as activate6_19_, user0_.activation_key as activati7_19_, user0_.avatar_url as avatar_u8_19_, user0_.banner_url as banner_u9_19_, user0_.description as descrip10_19_, user0_.email as email11_19_, user0_.first_name as first_n12_19_, user0_.lang_key as lang_ke13_19_, user0_.last_name as last_na14_19_, user0_.login as login15_19_, user0_.online as online16_19_, user0_.password_hash as passwor17_19_, user0_.reset_date as reset_d18_19_, user0_.reset_key as reset_k19_19_, user0_.test_data as test_da20_19_, 

SELECT COUNT(user0_.friendship) 其中friendship.friend在( ,选择F .friend FROM Friendship f where f.owner.id = COALESCE(?#{principle!= null?principal.id:user0_.null},user0_.id)) and friendship.owner.id = user0_.id as formula2_ from user user__ where user0_.login =?

SpEL/JPA正确实现了用user0_.id代替id,但还是有些东西丢失了? 此外,它似乎没有看到select count(user0_.friendship) from Friendship friendship where friendship.friend in (SELECT f.friend FROM Friendship f where f.owner.id = COALESCE(?#{principle != null ? principal.id : user0_.null},user0_.id)) and friendship.owner.id = user0_.id as formula2_部分的查询已被正确解析?

回答

1

我认为问题可能是id在SpEL上下文中是未知的。用

替换SpEL表达
COALESCE(?#{principle != null ? principal.id : null},id) 

应该这样做。

+0

试了一下,结果相同 –

1

对不起,完全错过了很明显的:

@Formula是一个Hibernate的事情。它对SpEL一无所知,并且评估这样的表达。

你可以做什么,你链接的例子是:在你的仓库中创建一个方法,添加一个@Query注释并在那里使用SpEL。

+0

在整个应用程序的很多地方,User用户实体被链接到其他实体,我不需要重新运行'@ Query'方法来拉取?或者我可以直接将'@ Query'添加到'@ Entity'注释类? –

+0

您可以将命名查询放在实体上(https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.named-queries),但这又是一个JPA功能并不支持SpEL。 –