【问题标题】:Can I refer a JPA entity within SpEL, on pageable findAll repository method我可以在可分页的 findAll 存储库方法上引用 SpEL 中的 JPA 实体吗
【发布时间】:2020-05-09 12:15:51
【问题描述】:

我有一个实体

@Data
@Entity
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name="component")
@Audited
public class Component implements Serializable {

    private static final long serialVersionUID = 0L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long Id;

    @Version
    private Long version;

    @Builder.Default
    private Boolean activated = true;

    private String name;


    @ManyToOne
    @JoinColumn(referencedColumnName="Id", nullable = true)
    @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
    private Organisation organisation;

}

...和一个存储库接口:

@Repository
@RepositoryRestResource(exported = false)
public interface ComponentRepository extends JpaRepository<Component, Long>, JpaSpecificationExecutor<Component>, RevisionRepository<Component, Long, Integer> {


     @Query("select c from Component c where 1 = ?#{@authorisation.isInternalUser() or @authorisation.isUserInOrg(#c) ? 1:0}")
      Page<Component> findAll(@Nullable Specification<Component> spec, Pageable pageable);

}

我的最终目标是以一种优雅的方式过滤掉当前登录用户不允许看到的实体。 我认为 SpEL 会是一个很好的方法,但是我找不到在表达式中传递实体引用“c”的方法。 另一种替代方法可能是将 JPQL 更改为这样的东西?

 @Query("select c from Component c where c.organisation = ?#{ @authorisation.getCurrentUserOrganisation()} or 1 = ?#{@authorisation.isInternalUser() ? 1:0}")

或者也许有一种方法可以用一些 SpEL 直接注释实体?

我尝试调试 Spring 源代码并了解它是如何工作的,但我所看到的只是在 SpEL 上下文评估中......只能访问 Pageable 对象和 JPA 规范。

提前谢谢你!

【问题讨论】:

  • 您确定您可以在 jpa 查询中访问此“@authorisation.isInternalUser()”吗?
  • 是的,SpEL 可以识别 bean 调用并且我的断点被拦截了。
  • 有了@authorisation.isUserInOrg(#c),它应该如何翻译成sql?每个Component c 都会调用它

标签: spring jpa jpql spring-el


【解决方案1】:

创建执行此操作的Specification&lt;Component&gt; spec

authorisation.isInternalUser() or @authorisation.isUserInOrg(#c) 

并与它一起使用

Page<Component> findAll(@Nullable Specification<Component> spec, Pageable pageable);

【讨论】:

  • 谢谢...我很快就阅读了规范,也许这就是我真正需要的!我现在试试,然后确认你的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 2019-07-24
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多