如何解决如何为Springboot JPA建立通用的通用存储库
这是我的模特:-
@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",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",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(),Sort.by(sortBy).ascending());
}
return employeeService.getAll(pageable);
}
}
我收到此错误:-
:Servlet [dispatcherServlet]中的Servlet.service() 路径[]引发异常[请求处理失败;嵌套异常 是org.springframework.dao.InvalidDataAccessApiUsageException:不是 实体:com.howtodoinjava.demo.model.IdCommon类;嵌套异常 是java.lang.IllegalArgumentException:不是实体:类 com.howtodoinjava.demo.model.IdCommon]的根本原因
java.lang.IllegalArgumentException:不是实体:类 com.howtodoinjava.demo.model.IdCommon
如上述错误所述,它不是实体。因此,我在@IdCommon中添加了@Entity批注。然后我得到了新的错误:-
org.springframework.beans.factory.BeanCreationException:错误 在类路径中创建名称为“ entityManagerFactory”的bean 资源 [org / springframework / boot / autoconfigure / orm / jpa / HibernateJpaConfiguration.class]: 调用init方法失败;嵌套异常为 org.hibernate.AnnotationException:无法使用注释实体 @Entity和@MappedSuperclass: com.howtodoinjava.demo.model.IdCommon
我该如何实现?我的要求是具有通用存储库类型。我将有许多类似的实体。为了避免很多代码,我应该使用泛型。
解决方法
已经有一段时间了,希望您已经有了解决方案。但是,对于其他面临相同问题的人,我将尝试找出您的解决方案无法正常工作的原因。
第一件事是,您的存储库必须使用@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);
}
}
并使用CommandLineRunner
运行它(懒惰地添加控制器)
@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]
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。