春季同一实体的两个存储库

时间:2019-10-08 18:25:33

标签: spring spring-boot spring-security java-8 spring-data-jpa

我的应用程序中有多个不同类型的用户,每种类型都有其自己的角色(显然还有权限)

我想使用spring数据剩余,但是这种功能只能对ADMIN_ROLE用户可用。

然后,我为每个实体创建了2个存储库,一个为管理员创建,另一个为其余用户创建:

@RepositoryRestResource(exported = false)
public interface MenuRepository extends JpaRepository<Menu, Integer> {

}

// -------------------------------------------------------------------

@RepositoryRestResource
@PreAuthorize("hasRole('ROLE_ADMIN')")
public @interface AdminRestRepository {
}

// -------------------------------------------------------------------

@AdminRestRepository
public interface AdminMenuRestRepository extends JpaRepository<Menu, Integer> {
}

问题在于,一旦我启动了应用程序,有时就会导出存储库,而在另一些时候,它不是...有任何线索吗?

1 个答案:

答案 0 :(得分:0)

我找到了对此问题的解释。

在单个spring应用程序中不可能有2个用于同一实体的存储库,因为存储库由实体类使用地图标识(例如,PersonRepository由Person类标识)。

可在此处找到来源:Multiple Repositories for the Same Entity in Spring Data Rest

作为一项工作,可以创建另一个实体并将其映射到相同的数据库表,然后为其创建另一个存储库(例如,我将拥有PersonRepository和Person2Repository,其中Person和Person2映射到同一张表)

我最终将使用基于Spring url的安全性,并通过其url保护每个其余端点。

希望这会有所帮助