Spring JPA:如何基于@Embedded属性编写JpaRepository查询?
解决Spring Data JPA查询@Embedded属性时的"No property 'cpf' found for type 'Patient'"错误
问题原因
Spring Data JPA的查询方法命名依赖实体类的属性路径,你的Patient类本身没有cpf属性,该属性嵌套在@Embedded的Person对象里,直接用existsByCpf会导致JPA无法识别属性路径。
解决方案
1. 修正Repository查询方法名(必须)
按照「嵌入属性名+内嵌属性名」的规则命名查询方法,格式为existsBy[嵌入属性变量名][内嵌属性名]:
@Repository public interface PatientRepository extends JpaRepository<Patient, UUID> { // 匹配Patient类中嵌入属性变量名Person(大写)的路径:Person.cpf boolean existsByPersonCpf(String cpf); }
2. 优化变量命名(推荐)
Java变量名遵循小驼峰规范,建议将Patient类中的嵌入属性变量名改为小写,避免和类名混淆:
@Data @Entity @Table(name = "tb_patient") public class Patient implements Serializable { // ... 其他代码保持不变 @Embedded private Person person; // 大写P改为小写p }
修改后Repository的方法名依然是existsByPersonCpf(JPA会自动将属性名首字母大写拼接),无需额外调整。
3. 同步Service层调用
确保Service中的方法调用和Repository的方法名一致:
@Service public class PatientService { final PatientRepository patientRepository; public PatientService(PatientRepository patientRepository) { this.patientRepository = patientRepository; } public boolean existsByCpf(String cpf) { return patientRepository.existsByPersonCpf(cpf); } }
额外注意
Controller中使用BeanUtils.copyProperties(person, patientModel)时,无论嵌入属性变量名是大写还是小写,BeanUtils都会自动将Person类的属性映射到Patient的嵌入属性中,无需额外配置。
内容的提问来源于stack exchange,提问作者glpsx
相关产品推荐
相关产品推荐

