我有一个实体层次结构,类似于这个。除了一些常见属性外,一些属性仅由少数子类型共享:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person {
private String firstName;
private String lastName
... further properties, getters and setters...
}
@Entity
public class Employee extends Person {
private String salary;
... further properties, getters and setters...
}
@Entity
public class BoardMember extends Person {
private String salary;
... further properties, getters and setters...
}
@Entity
public class ExternalMember extends Person {
private String clearanceLevel;
... further properties, getters and setters...
}
@Repository
public interface PersonRepository extends JpaRepository<Person, Long>, QuerydslPredicateExecutor<Person> {
}
我正在使用QueryDSL根据动态筛选条件搜索人员,例如:
@Service
@Transactional
public class PersonService {
@Autowired
PersonRepository personRepository;
public Page<Person> search(String firstName, String salary) {
var searchCriterias = new BooleanBuilder();
if (firstName != null) {
searchCriterias.and(QPerson.firstName.eq(firstName));
}
if (salary != null) {
searchCriterias.andAnyOf(
QPerson.person.as(QEmployee.class).salary.eq(salary),
QPerson.person.as(QBoardMember.class).salary.eq(salary),
);
}
personRepository.findAll(searchCriterias);
}
}
这似乎不是正确的方法,但是我遇到了很多错误,比如“salary”不是Person的成员。
处理分层实体搜索的各种方法有哪些?我更喜欢使用QueryDSL来保证类型安全,但使用Spring Data Specification的解决方案也可以。
编辑:使用15个以上不同的搜索条件可能会变得非常复杂。因此,我需要一种编程方法来制定它们。