我有两个名为约会
和客户端
的实体,我想获取给定客户端的所有约会。当我尝试这样做时,我正在努力处理以下错误消息。
2022-05-24 13:30:41.685 WARN 23252 --- [ XNIO-3 task-1].m.m.a.ExceptionHandlerExceptionResolver:Resolve[org.springframe.da.InvalidDataAccessApiUsageException:参数值[1000]与预期类型[ma.mycom.myapp.domain.Client(n/a)]不匹配;嵌套异常是java.lang.IllegalArgumentException:参数值[1000]与预期类型[ma.mycom.myapp.domain.Client(n/a)]不匹配
以下是我的实体:
Client.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
}
Appointment.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);
您的约会
类没有任何类型的名为“客户端id”的字段,它只知道它拥有的Client
实体。
在您的JPA存储库方法中,您只能使用实体的现有字段。
解决此问题的两种最标准的方法是:
@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
对象来简单地获得约会,然后简单地访问其约会
字段。
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);
// 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);