Отображение трех объектов не работает должным образом из-за отложенной / активной загрузки в JPA - PullRequest
0 голосов
/ 27 ноября 2018

Я картирую три объекта.Доктор, Клиент (который расширяет лицо) и Медицинская консультация.Смотрите мой код выше.Рассмотрим все модели класса с конструктором по умолчанию, конструктор со всеми полями, а также методы получения и установки:

@Entity
@Table (name= "person")

public abstract class Person {

@Id @GeneratedValue
protected Long id;
protected String name;
protected String email;
protected String password;

@OneToOne
protected Address address;

Теперь класс Доктор.

@Entity(name = "doctor")
public class Doctor extends Person{
@OneToMany(mappedBy="doctor" , fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JsonManagedReference(value = "job-historical")
private List<MedicalConsultation> medicalConsultations;

@Enumerated
private Type type;

@ElementCollection
private List<String> specialties;
public Doctor() {
        super();
    }

public Doctor(String name, String email, String password, Address address, 
        List<String> specialties, Type type, 
        List<MedicalConsultation> medicalConsultations) {

    super(name,email,password,address);
    this.setMedicalConsultations(medicalConsultations);
    this.setSpecialties(specialties);
    this.setType(type);
}

Мои конструкторы вызывают super() и устанавливают свои значения в соответствии с суперклассом и его собственными свойствами.То же самое происходит с клиентским классом.

@Entity(name = "client")
public class Client extends Person{

    @JsonManagedReference(value = "client-consultations-historical")
    @OneToMany(mappedBy="doctor" , fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private List<MedicalConsultation> medicalConsultations;

Здесь модель медицинской консультации, которая получает две другие модели

@Entity
@Table(name = "medical_consultation")
public class MedicalConsultation {

    @Id
    @GeneratedValue
    private Long id;

    @JsonBackReference(value = "job-historical")
    @ManyToOne
    @JoinColumn(name="doctor_fk")
    private Doctor doctor;

    @ManyToOne
    @JoinColumn(name="client_fk")
    @JsonBackReference( value = "client-consultations-historical")
    private Client client;

    @JsonFormat(pattern = "dd/MM/yyyy hh:mm")
    private Date date;

    private BigDecimal price;

Наконец, у нас возникла проблема: На моем контроллереЯ не могу получить полные данные медицинских консультаций.То есть я получил данные, удостоверение личности и цену, но я почему-то не получаю Клиента и Доктора.Но если я вызываю метод getDoctor() или getClient и возвращаю один из них, я вижу всю информацию.

См. Метод в классе RestControl:

@RestController
public class Control {

@Autowired
private PersonRepository personRepo;
@Autowired
private ClientRepository clientRepo;
@Autowired
private AddressRepository addressRepo;
@Autowired
private DoctorRepository doctorRepo;
@Autowired
private MedicalConsultationRepository consultationRepo;
@GetMapping("consultations")
    public List<MedicalConsultation> getConsultations() {
        List<MedicalConsultation> consultations = this.consultationRepo.findAll();
        return consultations;
    }

Может быть, что-то не так в картировании.Но я установил hibernate, чтобы показать sql, и он, очевидно, заставляет весь запрос получать все, что я хочу.См .:

Hibernate: 
    select
        medicalcon0_.id as id1_2_,
        medicalcon0_.client_fk as client_f4_2_,
        medicalcon0_.date as date2_2_,
        medicalcon0_.doctor_fk as doctor_f5_2_,
        medicalcon0_.price as price3_2_ 
    from
        medical_consultation medicalcon0_
Hibernate: 
    select
        client0_.id as id2_3_0_,
        client0_.address_id as address_7_3_0_,
        client0_.email as email3_3_0_,
        client0_.name as name4_3_0_,
        client0_.password as password5_3_0_,
        address1_.id as id1_0_1_,
        address1_.city as city2_0_1_,
        address1_.number as number3_0_1_,
        address1_.phone as phone4_0_1_,
        address1_.street as street5_0_1_,
        medicalcon2_.doctor_fk as doctor_f5_2_2_,
        medicalcon2_.id as id1_2_2_,
        medicalcon2_.id as id1_2_3_,
        medicalcon2_.client_fk as client_f4_2_3_,
        medicalcon2_.date as date2_2_3_,
        medicalcon2_.doctor_fk as doctor_f5_2_3_,
        medicalcon2_.price as price3_2_3_,
        client3_.id as id2_3_4_,
        client3_.address_id as address_7_3_4_,
        client3_.email as email3_3_4_,
        client3_.name as name4_3_4_,
        client3_.password as password5_3_4_ 
    from
        person client0_ 
    left outer join
        address address1_ 
            on client0_.address_id=address1_.id 
    left outer join
        medical_consultation medicalcon2_ 
            on client0_.id=medicalcon2_.doctor_fk 
    left outer join
        person client3_ 
            on medicalcon2_.client_fk=client3_.id 
    where
        client0_.id=? 
        and client0_.dtype='client'
Hibernate: 
    select
        doctor0_.id as id2_3_0_,
        doctor0_.address_id as address_7_3_0_,
        doctor0_.email as email3_3_0_,
        doctor0_.name as name4_3_0_,
        doctor0_.password as password5_3_0_,
        doctor0_.type as type6_3_0_,
        address1_.id as id1_0_1_,
        address1_.city as city2_0_1_,
        address1_.number as number3_0_1_,
        address1_.phone as phone4_0_1_,
        address1_.street as street5_0_1_,
        medicalcon2_.doctor_fk as doctor_f5_2_2_,
        medicalcon2_.id as id1_2_2_,
        medicalcon2_.id as id1_2_3_,
        medicalcon2_.client_fk as client_f4_2_3_,
        medicalcon2_.date as date2_2_3_,
        medicalcon2_.doctor_fk as doctor_f5_2_3_,
        medicalcon2_.price as price3_2_3_,
        client3_.id as id2_3_4_,
        client3_.address_id as address_7_3_4_,
        client3_.email as email3_3_4_,
        client3_.name as name4_3_4_,
        client3_.password as password5_3_4_ 
    from
        person doctor0_ 
    left outer join
        address address1_ 
            on doctor0_.address_id=address1_.id 
    left outer join
        medical_consultation medicalcon2_ 
            on doctor0_.id=medicalcon2_.doctor_fk 
    left outer join
        person client3_ 
            on medicalcon2_.client_fk=client3_.id 
    where
        doctor0_.id=? 
        and doctor0_.dtype='doctor'

Может кто-нибудь сказать мне, что происходит?

1 Ответ

0 голосов
/ 27 ноября 2018

попробуйте отобразить аннотацию, как показано ниже, на MedicalConsultation.

@ManyToOne(fetch = FetchType.EAGER)
private Doctor doctor;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...