我正在开发 Spring Boot 应用程序。
我们有服务层、Rest Controller 和 Dao 作为存储库。
我的数据库中有 20 到 30 个表,我不想为每个实体创建存储库并将其扩展到 CrudRepository。
例如:用户是一个实体,要对用户执行持久化操作,我必须创建扩展 CrudRepository 的 UserRepository。
与部门、公司等相同...
我想做的是,我将编写一个 BaseRepository 来扩展 CrudRepository,基础存储库应该接受所有实体并进行持久化操作。
有办法吗?
最佳答案
不要扩展 CrudRepository,它的功能全部与通用类型相关,将其扩展为通用实现是很麻烦的。您可能只想要一些直接使用 JPA 实体管理器的简单内容:
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
public class GenericRepository {
@Autowired
private EntityManager entityManager;
public <T, ID> T findById(Class<T> type, ID id) {
return entityManager.find(type, id);
}
}
关于spring - 为所有实体编写通用 spring jpa 存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53690995/