Spel格式化查询Spring Data JPA w / Spring Security

时间:2017-10-16 23:16:29

标签: spring-security spring-data-jpa

我有一个Spring Data JPA实体

@Entity    
public class User  {

    private static final long serialVersionUID = 1L;

    @Id
    private Long id;

我希望包含一个属性mutualFriends,它是查询用户principle(在Spring Security中)的查询结果,使用SpELEvaluationContext extension model ?:

根据SpEL示例,我提出了类似的结果:

@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是否可用或我收到错误:

  

引起:org.postgresql.util.PSQLException:没有指定值   参数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_, 

选择计数(user0_.friendship)     来自友谊的友谊     在哪里友谊。朋友在(         选择f.friend         来自友谊f         其中f.owner.id = COALESCE(?#{principle!= null?principal.id:user0_.null},user0_.id))         和friendship.owner.id = user0_.id为formula2_         来自用户user0_,其中user0_.login =?

SpEL / JPA正确实现用id替换user0_.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_部分似乎没有被正确解析?

2 个答案:

答案 0 :(得分:2)

对不起,完全错过了显而易见的事情:

@Formula是一个Hibernate的东西。它对SpEL和伤口一无所知,只评估这些表达方式。

您可以做什么,以及您链接的示例是:在您的存储库中创建方法,添加@Query注释并在其中使用SpEL。

答案 1 :(得分:1)

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

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

应该这样做。