我有兩個名為Appointementand的物體Client,我想獲取
給定客戶的所有約會。當我嘗試這樣做時,我正在努力處理以下錯誤訊息。
2022-05-24 13:30:41.685 WARN 23252 --- [XNIO-3 task-1] .mmaExceptionHandlerExceptionResolver:已解決 [org.springframework.dao.InvalidDataAccessApiUsageException:引數值 [1000] 與預期型別 [ma.mycom] 不匹配.myapp.domain.Client (n/a)]; 嵌套例外是 java.lang.IllegalArgumentException:引數值 [1000] 與預期型別不匹配 [ma.mycom.myapp.domain.Client (n/a)]]
這是我的物體:
客戶端.java
@Entity
@Table(name = "CLIENTS")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
//other attributes, getters, setters
}
約會.java
@Entity
@Table(name = "APPOINTMRNTS")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Appointment implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
//other attributes
@ManyToOne
@JoinColumn(name = "ID_CLIENT")
private Client client;
//getters, setters
}
控制器,以及我如何呼叫查詢:
List<Appointement> clientAppointements = appointementRepository.findAllByClient(idClient);
這是中使用的查詢AppointementRepository.java(我想這是問題的根源)
@Query(
name = "SELECT pe.* FROM APPOINTEMENTS pe INNER JOIN CLIENTS e ON pe.ID_CLIENT = e.ID WHERE e.id = ?1",
nativeQuery = true
)
List<Appointement> findAllByClient(Long idClient);
uj5u.com熱心網友回復:
您的Appointment類沒有任何型別的稱為“客戶端 ID”的欄位,它只知道Client它擁有的物體。
在您的 JPA 存盤庫方法中,您只能使用物體的現有欄位。
您可以解決此問題的兩種最標準的方法是:
1-在關系Appointment的一側添加欄位以Client使其成為雙向(我個人推薦這個)。您的Client物體將如下所示:
@Entity
@Table(name = "CLIENTS")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "client", fetch = FetchType.LAZY)
List<Appointment> appointments;
//other attributes, getters, setters
}
然后,您可以通過獲取一個Client物件來簡單地獲取約會,然后簡單地訪問它的appointments欄位。
List<Appointement> clientAppointements = clientRepository.findClientByField(field)
.getAppointments();
或者您甚至可以在存盤庫方法中獲得客戶的約會:
// in your appointment repository
@Query(value = "SELECT c.appointments FROM Client c WHERE c.id = :cId")
List<Appointment> getAppointmentsById(Long cId);
2-如果您不想建立雙向關系,則應在使用存盤庫方法Client搜索物件之前獲取該物件。Appointment
// in your appointment repository
List<Appointment> findByClient(Client client);
// then you can fetch it anywhere
Client client = clientRepository.findById(cliendId);
List<Appointment> clientAppointments = appointmentRepository.findByClient(client);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/481185.html
