【问题标题】:SpEL formatted Query Spring Data JPA w/ Spring SecuritySpEL 格式的 Query Spring Data JPA w/ Spring Security
【发布时间】:2018-03-28 13:35:06
【问题描述】:

我有一个 Spring Data JPA 实体

@Entity    
public class User  {

    private static final long serialVersionUID = 1L;

    @Id
    private Long id;

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

按照 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}

格式是否正确?

这里是当我得到异常时执行的休眠查询的相关部分:

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) 来自友谊友谊 在哪里friendship.friend( 选择 f.friend 来自友谊 f 其中 f.owner.id = COALESCE(?#{principle != null ? principal.id : user0_.null},user0_.id)) 和friendship.owner.id = user0_.id 作为公式2_ 来自用户 user0_ where 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_ 部分似乎没有被正确解析?

【问题讨论】:

    标签: spring-security spring-data-jpa


    【解决方案1】:

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

    @Formula 是一个休眠的东西。它对 SpEL 一无所知,并且会评估此类表达式。

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

    【讨论】:

    • 在整个应用程序的很多地方,User 实体链接到其他实体,我是否必须重新运行 @Query 方法来拉取?或者我可以将@Query 直接添加到@Entity 注释类吗?
    • 您可以在实体 (docs.spring.io/spring-data/jpa/docs/current/reference/html/…) 上放置命名查询,但这又是 JPA 功能,不支持 SpEL。
    【解决方案2】:

    我认为问题可能在于 id 在 SpEL 上下文中是未知的。将 SpEL 表达式替换为

    COALESCE(?#{principle != null ? principal.id : null},id)
    

    应该可以解决问题。

    【讨论】:

    • 试一试,同样的结果
    猜你喜欢
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 2018-03-31
    • 2018-08-31
    • 2021-08-27
    • 2014-08-31
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多