Spring Data JPA如何为多个实体构建通用存储库?

时间:2018-11-08 14:04:02

标签: java generics spring-data-jpa

我开始使用Spring Data JPA存储库。我们已经有一个使用Spring MVC的应用程序(没有Spring Boot或Spring Data JPA),我们在其中编写了Generic DAO类,该类处理几乎所有实体的基本CRUD操作。编写自定义DAO可以处理任何其他特殊操作。

现在,Spring数据JPA要求我们仅编写一个接口,其余部分都得到了照顾。

public interface PersonRepository extends JpaRepository<Person, Long> {

}

这很酷,但是我想知道是否可以在这里介绍泛型。

原因是,我的应用程序有许多实体,我们只需要对它们执行基本的CRUD操作,仅此而已。这意味着,对于每个实体,我们需要编写一个接口。尽管代码很少,但每个实体只能得到一个文件,我想这是可以避免的(是吗?)。

我的问题是,我可以写一个通用的Repository类吗?

public interface GenericRepository<T> extends JpaRepository<T, Long> {

}

这样我的服务类可以像这样

@Autowired
private GenericRepository<Person> personRepository;

public List<Person> findAll() {
     return this.personRepository.findAll();
}

对于一个基本操作,这将是一种更为简洁的方法,因为一个Repository接口可以处理许多实体。

编辑 事实证明,我确实可以如上所述创建存储库接口,但是当应用程序启动时,出现错误提示

Error creating bean with name 'genericRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object

这可能是由于通用类型

我不得不说我的实体本身是单独的类,并且不实现或扩展超级实体。如果他们这样做会有所帮助吗?

请朝正确的方向引导我。

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您可以这样做:

@NoRepositoryBean
public interface GenericRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
   //added custom common functionality for all the GenericRepository implementations
   public List<T> findByAttributeContainsText(String attributeName, String text);
}

public class GenericRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID>
    implements GenericRepository<T, ID> {

   private EntityManager entityManager;

   public GenericRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
    super(entityInformation, entityManager);
    this.entityManager = entityManager;
}

@Transactional
public List<T> findByAttributeContainsText(String attributeName, String text) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> cQuery = builder.createQuery(getDomainClass());
    Root<T> root = cQuery.from(getDomainClass());
    cQuery.select(root).where(builder.like(root.<String>get(attributeName), "%" + text + "%"));
    TypedQuery<T> query = entityManager.createQuery(cQuery);
    return query.getResultList();
}
}
public interface MyOtherRepository extends GenericRepository<Role, Long> {

}

在您的配置类中:

@Configuration
@EnableJpaRepositories(basePackages="com.myProject", repositoryBaseClass = 
GenericRepositoryImpl.class)
public class JpaConfig {

}
相关问题