我正在尝试创建一个通用的抽象存储库类来处理继承我的BaseModel类并覆盖保存行为的所有sql模型。
@Repository
public abstract class GenericRepository implements JpaRepository<BaseModel, Long> {
@Override
public <S extends BaseModel> S save(S baseModel) {
long timeStamp = System.currentTimeMillis();
if (baseModel.createdTimeStamp == 0) {
baseModel.createdTimeStamp = timeStamp;
baseModel.updatedTimeStamp = timeStamp;
} else {
baseModel.updatedTimeStamp = timeStamp;
}
super.save(baseModel);
return baseModel;
}
}
然后在我的任何控制器中自动装配此类:
@Autowired
GenericRepository genericRepository;
然而,当我运行我的春季启动应用程序时,我得到以下内容:
Field genericRepository in com.spring.springboot.rest.example.student.StudentResource required a bean of type 'com.spring.springboot.rest.example.student.GenericRepository' that could not be found.
Action:
Consider defining a bean of type 'com.spring.springboot.rest.example.student.GenericRepository' in your configuration.
答案 0 :(得分:1)
首先为您的通用仓库创建一个界面:
@NoRepositoryBean
public interface GenericRepository<T extends BaseModel, Long> extends JpaRepository<T, Long> {}
然后创建您的实现:
public class GenericRepositoryImpl<T extends BaseModel> extends SimpleJpaRepository<T, Long> implements GenericRepository<T, Long> {
@Override
public <S extends T> S save(S baseModel) {
long timeStamp = System.currentTimeMillis();
if (baseModel.createdTimeStamp == 0) {
baseModel.createdTimeStamp = timeStamp;
baseModel.updatedTimeStamp = timeStamp;
} else {
baseModel.updatedTimeStamp = timeStamp;
}
save(baseModel);
return baseModel;
}
}
最后,告诉Spring将其用作存储库的基类。在你的配置的某个地方..
@Configuration
@EnableJpaRepositories(repositoryBaseClass = GenericRepositoryImpl.class)
然后你可以像这样使用它:
public interface MyEntityRepository extends GenericRepository<MyEntity> {}
一些豆子:
@Autowired
private MyEntityRepository myEntityRepository;