【问题标题】:Secondary save method in a Spring Data JPA repo?Spring Data JPA 存储库中的辅助保存方法?
【发布时间】:2018-09-25 20:46:49
【问题描述】:
我有一个通过 Spring Data REST 导出并使用 Spring Security 保护的 Spring Data JPA 存储库。我还需要从不安全的端点将数据保存到此表,但我的 save() 方法是安全的。
由于https://jira.spring.io/browse/DATAREST-923,我无法创建第二个存储库。
我知道的唯一方法是每次在调用安全的save() 方法之前手动操作安全上下文。
有没有更好的办法?
【问题讨论】:
标签:
spring-security
spring-data-jpa
spring-data-rest
【解决方案1】:
如果您只保护save 方法,您可以尝试不安全地使用saveAndFlush 方法。
另一种方法 - customize your repo。首先 - 实现自定义 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 {
//...
}