【发布时间】: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都会调用它