jpa 如何使用嵌入式实体创建existsBy查询?

wljmcqd8  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(214)

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

个人.java

@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;

}

牙医.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;

}

牙科控制器.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));
    }

牙医服务.java

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

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

牙科知识库.java

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

    boolean existsByCpf(String cpf);
}

我正在尝试使用existsBy和Person的CPF列来过滤查询/代码。Person嵌入在牙医实体中。我如何才能正确实现这段代码?我正在尝试下面的方法,但我没有任何进展。
Spring正在为我返回此错误
导致的原因:找不到类型'Dentist'的属性'cpf'

  • 我只发布了我的部分代码,existsByCroNumber查询工作正常,其余的API也很好。*
vdzxcuhz

vdzxcuhz1#

您应该将存储库方法命名为existsByPersonCpf。

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

  boolean existsByPersonCpf(String cpf);
}

相关问题