Solucionado (ver solução)
Solucionado
(ver solução)
29
respostas

[Bug] Erro ao compilar query escolher médico aleatório

Estou recebendo um erro após implementar o método escolherMedicoAleatorioLivreNaData .

Geralmente venho acompanhando o curso e escrevendo o código manualmente, porém tive um problema com essa query, então decidi voltar no começo do curso refazendo o projeto e copiando os códigos e nomes dos arquivos do projeto final, e mesmo assim parei no mesmo erro. Testei o projeto final disponibilizado pelo professor com o meu banco de dados, e funcionou perfeitamente (foi necessário apenas remover as migrations). Os códigos estão no mesmo estado da aula atual, não copiei as partes do projeto que o professor ainda não passou.

Gostaria de saber se esse problema é solucionado mais posteriormente no curso? tendo em vista que o projeto final rodou normalmente.

A primeira parte da StackTrace foi a seguinte:

2023-06-11T10:34:47.123-03:00  INFO 12140 --- [  restartedMain] .s.b.a.l.ConditionEvaluationReportLogger : 

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-06-11T10:34:47.167-03:00 ERROR 12140 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'consultaController': Unsatisfied dependency expressed through field 'agenda': Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in ___.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime); 
- Reason: Validation failed for query for method public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime)

  ...

- Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in ___.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime); 
- Reason: Validation failed for query for method public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime)

    ...

- Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'medicoRepository' defined in ___.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime); 
- Reason: Validation failed for query for method public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime)

    ...

- Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime); 
- Reason: Validation failed for query for method public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime)

    ...

- Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract ___.medico.Medico ___.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(___.medico.Especialidade,java.time.LocalDateTime)
29 respostas

E a segunda parte da StackTrace:

Caused by: java.lang.IllegalArgumentException: org.hibernate.query.sqm.InterpretationException: Error interpreting query [    select m from Medico m
    where
    m.ativo = 1
    and
    m.especialidade = :especialidade
    and
    m.id not in(
        select c.medico.id from Consulta c
        where
        c.data = :data
        and
        c.motivoCancelamento is null
    )
    order by rand()
    limit 1
]; this may indicate a semantic (user query) problem or a bug in the parser [    select m from Medico m

    Repete a query ...

]

    ...

Caused by: org.hibernate.query.sqm.InterpretationException: Error interpreting query [    select m from Medico m

    Repete a query ...

]; this may indicate a semantic (user query) problem or a bug in the parser [    select m from Medico m

    Repete a query ...

]

    ...

Caused by: java.lang.IllegalArgumentException: Can't compare test expression of type [BasicSqmPathSource(ativo : Boolean)] with element of type [basicType@15(java.lang.Integer,4)]

Oi Juliu!

Troque esse trecho:

m.ativo = 1

Para:

m.ativo = true

Fiz a substituição e apresentou o mesmo erro. A primeira parte do erro é identica, mas a segunda parte ta abaixo:

Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract __.medico.Medico __.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(__.medico.Especialidade,java.time.LocalDateTime); 
Reason: Validation failed for query for method public abstract __.medico.Medico __.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(__.medico.Especialidade,java.time.LocalDateTime)

Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract __.medico.Medico __.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(__.medico.Especialidade,java.time.LocalDateTime)

Caused by: java.lang.IllegalArgumentException: org.hibernate.query.sqm.InterpretationException: Error interpreting query [    select m from Medico m
    where
    m.ativo = true
    and
    m.especialidade = :especialidade
    and
    m.id not in(
        select c.medico.id from Consulta c
        where
        c.data = :data
        and
        c.motivoCancelamento is null
    )
    order by rand()
    limit 1
]; this may indicate a semantic (user query) problem or a bug in the parser [    select m from Medico m
Repete a query ...
]

Caused by: org.hibernate.query.sqm.InterpretationException: Error interpreting query [    select m from Medico m
Repete a query ...
]; this may indicate a semantic (user query) problem or a bug in the parser [    select m from Medico m
Repete a query ...
]

Caused by: java.lang.IllegalArgumentException: org.hibernate.query.SemanticException: Could not resolve attribute 'motivoCancelamento' of '__.consulta.Consulta'

Caused by: org.hibernate.query.SemanticException: Could not resolve attribute 'motivoCancelamento' of '__.consulta.Consulta'

Existe algum módulo que eu não tenha instalado para não estar funcionando a query?

Deixei o código do medico repository abaixo. O import da anotação Query funcionou corretamente.

public interface MedicoRepository extends JpaRepository<Medico, Long> {

  Page<Medico> findAllByAtivoTrue(Pageable paginacao);

      @Query("""
            select m from Medico m
            where
            m.ativo = true
            and
            m.especialidade = :especialidade
            and
            m.id not in(
                select c.medico.id from Consulta c
                where
                c.data = :data
                and
                c.motivoCancelamento is null
            )
            order by rand()
            limit 1
        """)
    Medico escolherMedicoAleatorioLivreNaData(Especialidade especialidade, LocalDateTime data);
}
solução!

O erro agora: Could not resolve attribute 'motivoCancelamento' of '__.consulta.Consulta'

Verifica na sua classe Consulta se tem o atributo motivoCancelamento.

Ola estou com o mesmo problema e a minha Entidade Consulta possui o atributo motivoCancelamento

package com.med.voll.api.domain.consulta;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import com.med.voll.api.domain.medico.Medico;
import com.med.voll.api.domain.paciente.Paciente;

import java.time.LocalDateTime;

@Table(name = "consultas")
@Entity(name = "Consulta")
@Getter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = "id")
public class Consulta {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "medico_id")
    private Medico medico;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "paciente_id")
    private Paciente paciente;

    private LocalDateTime data;

    @Column(name = "motivo_cancelamento")
    @Enumerated(EnumType.STRING)
    private MotivoCancelamento motivoCancelamento;

    public void cancelar(MotivoCancelamento motivo) {
        this.motivoCancelamento = motivo;
    }

}

Consegui resolver o problema adicionando essa resolução no arquivo repositorio MedicoRepository https://cursos.alura.com.br/forum/topico-exception-ao-compilar-o-codigo-301538

Porem adicionei um outro ajuste mensionado nesse topico que é alterar o

m.ativo = 1 -> m.ativo = true

Ficou Assim e parou de dar exception ao compilar, provavelmente tinha alguma espaço ou a sintaxe do sql que estava errada.

@Query("""
        select m from Medico m
        where
        m.ativo = true
        and
        m.especialidade = :especialidade
        and
        m.id not in(
            select c.medico.id from Consulta c
            where
            c.data = :data
            and
            c.motivoCancelamento is null
        )
        order by rand()
        limit 1
    """)
    Medico escolherMedicoAleatorioLivreNaData(Especialidade especialidade, LocalDateTime data);

Estou com o mesmo problema:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'consultaController': Unsatisfied dependency expressed through field 'agenda': Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in med.voll.api.domain.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract java.lang.Boolean med.voll.api.domain.medico.MedicoRepository.findAtivoById(java.lang.Long); Reason: Validation failed for query for method public abstract java.lang.Boolean med.voll.api.domain.medico.MedicoRepository.findAtivoById(java.lang.Long) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:713) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:693) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:133) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:482) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1416) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:597) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:941) ~[spring-context-6.0.9.jar:6.0.9] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:608) ~[spring-context-6.0.9.jar:6.0.9] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:733) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:435) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1305) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1294) ~[spring-boot-3.1.0.jar:3.1.0] at med.voll.api.ApiApplication.main(ApiApplication.java:10) ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-3.1.0.jar:3.1.0]

A Query está correta, validei no MySQL:

public interface MedicoRepository extends JpaRepository<Medico, Long> {

Page<Medico> findAllByAtivoTrue(Pageable paginacao);

@Query("""
        select m from Medicos m
        where m.ativo = 1
        and m.especialidade = :especialidade
        and m.id not in(select c.medico_id from Consultas c
                        where c.data = :data)
        order by rand()
        limit 1
        """)
Medico escolherMedicoAleatorioLivreNaData(Especialidade especialidade, LocalDateTime data);

@Query( """
        select m.ativo
        from Medicos m
        where
        m.id = :id
        and m.ativo = 1
        """)
Boolean findAtivoById(Long id);

}

JesSé, no seu caso o problema é no método findAtivoById: "Reason: Validation failed for query for method public abstract java.lang.Boolean med.voll.api.domain.medico.MedicoRepository.findAtivoById(java.lang.Long)"

Manda o código do seu reposit

Jessé, suas consultas estão incorretas.

Estão com from Medicos m, mas na verdade deveria ser Medico (no singular, que é o nome da entidade).

Achei que seria o nome da tabela conforme está em Table na Classe Medico. Porém alterei e retorna esse erro.

@Table(name = "medicos") @Entity(name = "Medico") @Getter @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(of = "id") public class Medico {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String nome;
private String email;
private String telefone;
private String crm;
@Enumerated(EnumType.STRING)
private Especialidade especialidade;
@Embedded
private Endereco endereco;
private boolean ativo;

public Medico(DadosCadastroMedico dados) {
    this.nome = dados.nome();
    this.email = dados.email();
    this.telefone = dados.telefone();
    this.crm = dados.crm();
    this.endereco = new Endereco(dados.endereco());
    this.especialidade = dados.especialidade();
    this.ativo = true;
}

public void atualizarInformacoes(DadosAtualizacaoMedico dados) {
    if (dados.nome() != null){
        this.nome = dados.nome();
    }
    if (dados.telefone() != null){
        this.telefone = dados.telefone();
    }
    if (dados.endereco() != null){
        this.endereco.atualizaInformacoes(dados.endereco());
    }

}

public void excluir() {
    this.ativo = false;
}

}

Fiz as alterações e retorna:

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled. 2023-06-23T11:11:39.242-03:00 ERROR 14076 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'consultaController': Unsatisfied dependency expressed through field 'agenda': Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in med.voll.api.domain.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime); Reason: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:713) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:693) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:133) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:482) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1416) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:597) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:941) ~[spring-context-6.0.9.jar:6.0.9] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:608) ~[spring-context-6.0.9.jar:6.0.9] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:733) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:435) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1305) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1294) ~[spring-boot-3.1.0.jar:3.1.0] at med.voll.api.ApiApplication.main(ApiApplication.java:10) ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-3.1.0.jar:3.1.0]

É o mesmo nome do @Entity.

Qual erro deu? Na sua mensagem anterior não veio o erro, só o código da entidade Medico

Lembre de alterar a outra consulta também:

select m from Medico m
        where m.ativo = true
        and m.especialidade = :especialidade
        and m.id not in(select c.medico.id from Consulta c
                        where c.data = :data)
        order by rand()
        limit 1

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled. 2023-06-23T11:16:55.572-03:00 ERROR 19716 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'consultaController': Unsatisfied dependency expressed through field 'agenda': Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in med.voll.api.domain.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime); Reason: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:713) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:693) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:133) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:482)

Sim, alterei tudo, não consigo entender o motivo do erro. Ja ajustei as consultas conforme me passou, no repositorio. e mesmo assim:

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled. 2023-06-23T11:18:14.850-03:00 ERROR 17420 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'consultaController': Unsatisfied dependency expressed through field 'agenda': Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in med.voll.api.domain.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime); Reason: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:713) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:693) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:133) ~[spring-beans-6.0.9.jar:6.0.9]

Confere se a sua consulta está exatamente assim:

select m from Medico m
        where m.ativo = true
        and m.especialidade = :especialidade
        and m.id not in(select c.medico.id from Consulta c
                        where c.data = :data)
        order by rand()
        limit 1

Não foi apenas o from Medicos que foi alterado na consulta anterior. Tinha mais erros.

E posta aqui o erro completo que saiu no console.

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled. 2023-06-23T11:18:14.850-03:00 ERROR 17420 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'consultaController': Unsatisfied dependency expressed through field 'agenda': Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in med.voll.api.domain.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime); Reason: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:713) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:693) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:133) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:482) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1416) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:597) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:941) ~[spring-context-6.0.9.jar:6.0.9] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:608) ~[spring-context-6.0.9.jar:6.0.9] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:733) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:435) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:311) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1305) ~[spring-boot-3.1.0.jar:3.1.0] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1294) ~[spring-boot-3.1.0.jar:3.1.0] at med.voll.api.ApiApplication.main(ApiApplication.java:10) ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'agendaDeConsultas': Unsatisfied dependency expressed through field 'medicoRepository': Error creating bean with name 'medicoRepository' defined in med.voll.api.domain.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime); Reason: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:713) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:693) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:133) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:482) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1416) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:597) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1417) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1337) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:710) ~[spring-beans-6.0.9.jar:6.0.9] ... 25 common frames omitted

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'medicoRepository' defined in med.voll.api.domain.medico.MedicoRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime); Reason: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1770) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:598) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:254) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1417) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1337) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:710) ~[spring-beans-6.0.9.jar:6.0.9] ... 39 common frames omitted

Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime); Reason: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:115) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:99) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:88) ~[spring-data-commons-3.1.0.jar:3.1.0] at java.base/java.util.Optional.map(Optional.java:260) ~[na:na] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.(QueryExecutorMethodInterceptor.java:88) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:357) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:279) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.util.Lazy.getNullable(Lazy.java:245) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:285) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:132) ~[spring-data-jpa-3.1.0.jar:3.1.0] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1816) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1766) ~[spring-beans-6.0.9.jar:6.0.9] ... 49 common frames omitted

Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime); Reason: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.data.repository.query.QueryCreationException.create(QueryCreationException.java:101) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:115) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:99) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new$0(QueryExecutorMethodInterceptor.java:88) ~[spring-data-commons-3.1.0.jar:3.1.0] at java.base/java.util.Optional.map(Optional.java:260) ~[na:na] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.(QueryExecutorMethodInterceptor.java:88) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:357) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:279) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.util.Lazy.getNullable(Lazy.java:245) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.util.Lazy.get(Lazy.java:114) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:285) ~[spring-data-commons-3.1.0.jar:3.1.0] at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:132) ~[spring-data-jpa-3.1.0.jar:3.1.0] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1816) ~[spring-beans-6.0.9.jar:6.0.9] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1766) ~[spring-beans-6.0.9.jar:6.0.9] ... 49 common frames omitted Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract med.voll.api.domain.medico.Medico med.voll.api.domain.medico.MedicoRepository.escolherMedicoAleatorioLivreNaData(med.voll.api.domain.medico.Especialidade,java.time.LocalDateTime) at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:100) ~[spring-data-jpa-3.1.0.jar:3.1.0] at org.springframework.data.jpa.repository.query.SimpleJpaQuery.(SimpleJpaQuery.java:70) ~[spring-data-jpa-3.1.0.jar:3.1.0] at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:60) ~[spring-data-jpa-3.1.0.jar:3.1.0] at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:170) ~[spring-data-jpa-3.1.0.jar:3.1.0] at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:252) ~[spring-data-jpa-3.1.0.jar:3.1.0] at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:95) ~[spring-data-jpa-3.1.0.jar:3.1.0] at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:111) ~[spring-data-commons-3.1.0.jar:3.1.0] ... 61 common frames omitted

Tinha um erro na consulta anterior que mandei. Tava from Consultas ao ínves de from Consulta.

O código correto:

@Query("""
            select m from Medico m
            where
            m.ativo = true
            and
            m.especialidade = :especialidade
            and
            m.id not in(
                select c.medico.id from Consulta c
                where
                c.data = :data
            )
            order by rand()
            limit 1
            """)
    Medico escolherMedicoAleatorioLivreNaData(Especialidade especialidade, LocalDateTime data);

    @Query("""
            select m.ativo
            from Medico m
            where
            m.id = :id
            """)
    Boolean findAtivoById(Long id);

Fiz essa alteração, o erro de cima continua o mesmo, mas gerou erro de sintaxe no sql:

... 61 common frames omitted

Caused by: java.lang.IllegalArgumentException: org.hibernate.query.sqm.InterpretationException: Error interpreting query [select m from Medico m where m.ativo = 1 and m.especialidade = :especialidade and m.id not in(select c.medico_id from Consulta c where c.data = :data) order by rand() limit 1 ]; this may indicate a semantic (user query) problem or a bug in the parser [select m from Medico m where m.ativo = 1 and m.especialidade = :especialidade and m.id not in(select c.medico_id from Consulta c where c.data = :data) order by rand() limit 1 ]

package med.voll.api.domain.medico;

import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param;

import java.time.LocalDateTime;

public interface MedicoRepository extends JpaRepository<Medico, Long> {

Page<Medico> findAllByAtivoTrue(Pageable paginacao);

@Query("""
        select m from Medico m
        where m.ativo = true
        and m.especialidade = :especialidade
        and m.id not in(select c.medico_id from Consulta c
                        where c.data = :data)
        order by rand()
        limit 1
        """)
Medico escolherMedicoAleatorioLivreNaData(Especialidade especialidade, LocalDateTime data);

@Query( """
        select m.ativo
        from Medico m
        where
        m.id = :id
        """)
Boolean findAtivoById(Long id);

}

Sua consulta está errada ainda.

Apaga a sua consulta inteira e copia daqui:

@Query("""
            select m from Medico m
            where
            m.ativo = true
            and
            m.especialidade = :especialidade
            and
            m.id not in(
                select c.medico.id from Consulta c
                where
                c.data = :data
            )
            order by rand()
            limit 1
            """)

Rodrigo, muito obrigado. Era isso mesmo. Pode so me explicar porque não passamos a query literal (A que executamos no MySQL)? Outra dúvida, não entendi o uso do c.medico.id. Isso é de interpretação do JPA em relação aos objetos na classe? select c.medico.id from Consulta c where c.data = :data

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Sim é da JPA. JPA não utiliza SQL puro por padrão e sim o JPQL.

Bons estudos!