Spring Data JPA repo 中的辅助保存方法?

Secondary save method in a Spring Data JPA repo?

我有一个 Spring Data JPA 存储库,通过 Spring Data REST 导出并使用 Spring Security 进行保护。我还需要从不安全的端点将数据保存到此 table,但我的 save() 方法是安全的。

我无法创建第二个存储库,因为 https://jira.spring.io/browse/DATAREST-923

我知道的唯一方法是每次调用安全 save() 方法之前手动操作安全上下文。

有没有更好的方法?

如果您只保护 save 方法,您可以尝试使用不安全的 saveAndFlush 方法。

另一种方法 - customize your repo。首先 - 实施自定义存储库,例如:

public interface CustomRepo {
    MyEntity saveUnsecured(MyEntity entity);
}

@Repository
public class CustomRepoImpl implements CustomRepo {

    private final EntityManager em;

    public CustomRepoImpl(EntityManager em) {
        this.em = em;
    }

    @Transactional
    @Override
    public MyEntity saveUnsecured(MyEntity entity) {

        if (entity.getId() == null) {
            em.persist(entity);
            return entity;
        } else {
            return em.merge(entity);
        }
    }
}

然后从自定义一个扩展您的存储库:

public interface MyEntityRepo extends JpaRepository<MyEntity, Long>, CustomRepo {
    //...
}