Spring Data JPA -我如何使用嵌入式实体进行existsBy查询?



我是Spring的初学者,所以如果我犯了一些愚蠢的错误,我很抱歉。

位于

@Embeddable
@Data
public class Person {
@Column(nullable = false, length = 11)
private String cpf;
@Column(name = "full_name", nullable = false, length = 60)
private String fullName;
@Column(nullable = false)
private String birthdate;
@Column(name = "email", nullable = true, length = 30)
private String emailAddress;
@Column(name = "cellphone_number", nullable = true, length = 11)
private String cellphoneNumber;
@Embedded
private Address address;
}

Dentist.java

@Data
@Entity
@Table(name = "tb_dentists")
public class Dentist implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "dentist_id")
private UUID id;
@Column
private LocalDateTime registrationDate;
@Column(nullable = false, unique = true, length = 6)
private String croNumber;
@Embedded
private Person person;
}

DentistController.java

@PostMapping
public ResponseEntity<Object> saveDentist(@RequestBody @Valid Dentist dentistDto, Person person) {
if(dentistService.existsByCroNumber(dentistDto.getCroNumber())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("CONFLICT: CRO number is already in use!");
}
if(dentistService.existsByPerson_Cpf(person.getCpf())) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("CONFLICT: CPF number is already in use!");
}
var dentistModel = new Dentist();
BeanUtils.copyProperties(dentistDto, dentistModel);
dentistModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(dentistService.save(dentistModel));
}

DentistService.java

public boolean existsByCroNumber(String croNumber) {
return dentistRepository.existsByCroNumber((croNumber));
}
public boolean existsByPerson_Cpf(String cpf) {
return dentistRepository.existsByCpf((cpf));
}
}

DentistRepository.java

@Repository
public interface DentistRepository extends JpaRepository<Dentist, UUID> {
boolean existsByCroNumber(String croNumber);
boolean existsByCpf(String cpf);
}

我试图使用existsBy和Person的CPF列过滤查询/代码。Person嵌入到牙医实体中。我怎样才能正确地实现这段代码?我正在尝试如下所示,但我得到任何地方。

Spring为我返回这个错误

引起的:org.springframework.data.mapping.PropertyReferenceException:不查找牙医类型的cpf属性

我只是发布了我的代码的一部分,查询existsbycronnumber工作正常,API的其余部分也很好。

你应该将你的repo方法命名为existsByPersonCpf。

@Repository
public interface DentistRepository extends JpaRepository<Dentist, UUID> {
boolean existsByCroNumber(String croNumber);
boolean existsByPersonCpf(String cpf);
}

最新更新