[英]Spring boot, storing CRUD operations in abstract service
I have two JPA entites like我有两个 JPA 实体,例如
@Entity
@Table(name = "A")
public class A {...}
@Entity
@Table(name = "B")
public class B {...}
And services like和类似的服务
@Service
public class AServiceImpl implements AService {
@Autowired
private ARepository aRepository;
public void create() {...}
public void update(long id) {...}
public void doA() {...}
}
@Service
public class BServiceImpl implements BService {
@Autowired
private BRepository bRepository;
public void create() {...}
public void update(long id) {...}
public void doB() {...}
}
So, in methods create
and update
I have code what differs only by repository.因此,在
create
和update
方法中,我的代码仅因存储库而异。 I would like to store crud methods in some other, basic service, but do not really understand how could I manage repository inheritance.我想将 crud 方法存储在其他一些基本服务中,但我不太了解如何管理存储库 inheritance。 Any help, please.
任何帮助,请。
IMP: This code is compiling, I havent tested it. IMP:这段代码正在编译,我还没有测试过。
I think you can use Genarics over here.我想你可以在这里使用 Genaris。
public class RepositoryService <R extends JpaRepository<T, Long>, T> {
@Autowired R repository;
public void insert(T object) {
repository.save(object);
}
}
How to effectively use these reporitories, that details you can refer to this baeldung article - https://www.baeldung.com/spring-autowire-generics如何有效地使用这些reporitories,细节可以参考这篇baeldung文章 - https://www.baeldung.com/spring-autowire-generics
Update: This is an alternate approach you can try out更新:这是您可以尝试的另一种方法
public abstract class RepositoryService <T>{
abstract Class getRepositoryClass();
Map<Class, GenericRepository> repositories;
@Autowired
List<GenericRepository> repositoriesList;
@PostConstruct
public void setupMap() {
// Convert List into Map, with the class of Objest to be saved.
}
public void insert(T object) {
repositories.get(object.getClass()).save(object);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.