当前位置: 首页 > 知识库问答 >
问题:

如何为Springboot JPA建立通用的通用存储库

晋西岭
2023-03-14

以下是我的模型:-

    @MappedSuperclass
public class IdCommon {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Version
    private Long version;

    @CreatedBy
    @Column(name = "created_by")
    private String createdBy;

    @CreatedDate
    private Instant created;

    @LastModifiedBy
    @Column(name = "updated_by")
    private String updatedBy;

    @LastModifiedDate
    private Instant updated;

}



    @Entity
@Table(name="TBL_EMPLOYEES")
public class EmployeeEntity extends IdCommon {
    
    @Column(name="first_name")
    private String firstName;
    
    @Column(name="last_name")
    private String lastName;
    
    @Column(name="email", nullable=false, length=200)
    private String email;
    
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "EmployeeEntity [id=" + 0 + ", firstName=" + firstName +
                ", lastName=" + lastName + ", email=" + email   + "]";
    }
}

我的存储库和服务:-

@Repository
public interface CommonRepository<E extends IdCommon> extends JpaRepository<E, Long>, 
JpaSpecificationExecutor<E> {

  }

 @Service
 public class EmployeeService {

//@Autowired
EmployeeRepository repository;

//@Autowired
CommonRepository<EmployeeEntity> commonRepository;

@Autowired
public EmployeeService(EmployeeRepository repository, CommonRepository<EmployeeEntity> commonRepository) {
    this.repository = repository;
    this.commonRepository = commonRepository;
}

public Page<EmployeeEntity> getAll(Pageable pageable){
    Specification<EmployeeEntity> specification = (Specification<EmployeeEntity>) (root, query, builder) -> null;
    return commonRepository.findAll(specification, pageable);
}
}

控制器:-

    @RestController
@RequestMapping(path = "/employee")
public class EmployeeController2 {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping(path = "/all")

    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query",
                    value = "page number"),
            @ApiImplicitParam(name = "size", dataType = "integer", paramType = "query",
                    value = "Number of records per page."),
    })
    public Page<EmployeeEntity> getAll(@RequestParam(value = "sortBy", required = false, defaultValue = "created") String sortBy,
                                       @ApiIgnore Pageable pageable,
                                       @ApiParam(value = "sortDirection (desc/asc)")
                                       @RequestParam(value = "sortDirection", required = false, defaultValue = "asc") String sortDirection){
        if (sortDirection.equals("desc")) {
            pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(sortBy).descending());
        } else {
            pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(sortBy).ascending());
        }
        return employeeService.getAll(pageable);
    }
}

org.springframework.beans.factory.beanCreationException:创建类路径资源[org/springframework/boot/autocconfigure/orm/jpa/hibernatejpaconfiguration.class]中定义的名为“Entity ManagerFactory”的bean时出错:调用init方法失败;嵌套异常为org.hibernate.AnnotationException:不能同时用@entity和@MappedSuperClass:com.howtoDoinjava.demo.model.idCommon对实体进行注释

我如何实现这一点?我的要求是具有通用存储库类型。我会有很多类似的实体。为了避免很多代码,我应该使用泛型。

共有1个答案

於意蕴
2023-03-14

现在已经有一段时间了,我希望你已经得到了你的解决方案。但是,对于其他面临同样问题的人,我会试着解释为什么你的解决方案不起作用。

第一件事是,您的存储库必须用@norepositorybean进行注释,如下所示:

@NoRepositoryBean
public interface CommonRepository<E extends IdCommon> extends JpaRepository<E, Long>, JpaSpecificationExecutor<E> {}

并将在employeeRepository中显示:

public interface EmployeeRepository extends CommonRepository<EmployeeEntity> {
    //you can override some or all of the methods if necessary
}
@Service
public class EmployeeService {

    private EmployeeRepository empRepository;

    public EmployeeService(EmployeeRepository repository) {
        this.empRepository = repository;
    }

    public void saveEmployee(EmployeeEntity entity) {//I added this for a test
        empRepository.save(entity);
    }
    
    public Page<EmployeeEntity> getAll(Pageable pageable) {
        Specification<EmployeeEntity> specification = (Specification<EmployeeEntity>) (root, query, builder) -> null;
        return empRepository.findAll(specification, pageable);
    }
}
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    @Autowired
    private EmployeeService service;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        EmployeeEntity entity = new EmployeeEntity();
        entity.setEmail("aa@so.com");
        entity.setFirstName("First name");
        entity.setLastName("Last name");
        
        service.saveEmployee(entity);
        
        Page<EmployeeEntity> page = service.getAll(PageRequest.of(0, 1));
        page.getContent().stream().forEach(System.out::println); //output: EmployeeEntity [id=0, firstName=First name, lastName=Last name, email=aa@so.com]
    }

}
 类似资料:
  • 我有一个通用实体,我想使用JPA持久化,以便它的通用值存储在单个列中。简化的实体类如下所示: 类型唯一标识泛型值的类,并且允许具有相同类的多个类型: 我没有找到如何使用Hibernate保持这种泛型类的方法。我找到了替代方法和变通方法,但它们在我看来并不理想。我考虑了以下选项: > 将值的类型设置为JsonNode,并将其类型类标记为com。弗拉德米尔恰。冬眠类型json。JsonBinaryTy

  • 我开始使用SpringDataJPA存储库。我们已经有一个应用程序使用了Spring MVC(无Spring Boot或Spring数据JPA),在那里我们编写了一个Generic DAO类,该类处理我们拥有的几乎所有实体的基本CRUD操作。任何其他特殊操作都可以通过编写自定义DAO来处理。 现在,Spring data JPA让事情变得非常简单,只需要我们编写一个接口,剩下的就交给我们了。 这很

  • 我们正在研究一个包含大量DB表的Restful项目。虽然对这些表的操作几乎相同,主要是插入/更新/删除/提取(insert/update/delete/fetch)。 我的问题是: 我们是否必须为我们创建的每一个实体(域类)创建一个存储库(扩展JpaRepository),或者,有一个选项可以为所有实体创建一个能够处理上述所有功能的GenericRepository?即为所有人提供一个单一的Gen

  • 我见过存储库模式的各种用法。我倾向于一种我很少看到的模式,我想知道这是否有充分的理由。 例子: 利益 构造函数将是内部的,只能通过工厂模式访问,所以我不担心这里的复杂性。 IPerson 强制实现 Save() 方法,但教师不需要知道它是如何持久化的 工作原理类似于实体框架代理对象 我可以在 Iperson 对象上调用 Save(),而无需知道它是老师 应用- 欺骗 > 业务对象不再是普通的旧C#

  • 本文向大家介绍如何用C语言建立函数之间的通信?,包括了如何用C语言建立函数之间的通信?的使用技巧和注意事项,需要的朋友参考一下 函数之间通过参数和返回值进行通信。 'C'功能的服务器场如下- 例如,void mul(int x,int y) 返回值及其类型 一个函数可能会也可能不会将值发送回调用函数。 这将通过使用return语句来完成 返回类型为void,int,float,char和doubl

  • 问题内容: 我试图通过数据库链接调用存储过程。代码看起来像这样: 当我从package_name所属的相同数据库实例和模式运行此程序时,我可以很好地运行它。但是,当我通过数据库链接运行它((对存储的过程名称进行必要的修改等)时,我得到一个oracle错误:ORA-24338:语句句柄未执行。 此代码在dblink上的修改后的版本如下所示: 问题答案: 关于另一个问题,我记得package_name