I am having trouble querying a nested list of objects with Spring Data JPA.
Here are my Entities:
public class Shipment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(updatable = false, nullable = false)
private Long id;
@CreationTimestamp
@Column(updatable = false)
private Date createdAt;
@UpdateTimestamp
private Date updatedAt;
private String orderId;
private String deliveryId;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "shipment")
private List<Packet> packets;
// constructors, getters, setters omitted
}
and the nested List:
@Entity
public class Packet {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(updatable = false, nullable = false)
private Long id;
@CreationTimestamp
@Column(updatable = false)
private Date createdAt;
@UpdateTimestamp
private Date updatedAt;
private String packetId;
@Enumerated(EnumType.STRING)
private PacketType packetType;
}
Then I have a simple rest endpoint:
@GetMapping(path = "/shipments", produces = "application/json")
public List<ShippingIds> getShipments(SearchCriteria searchCriteria) {
List<Shipment> shipments = shipmentService.getShipmentIds(searchCriteria);
return buildShipmentIds(shipments);
}
And I am using the SearchCriteria as queryParams (/shipments?packetId={packetId}&orderId={orderId}&deliveryId={deliveryId}...
And my Service where I use query by example:
public List<Shipment> getShipmentIds(SearchCriteria searchCriteria) {
Shipment shipment = Shipment.builder()
.orderId(searchCriteria.getOrderId())
.deliveryId(searchCriteria.getDeliveryId())
.packetId(searchCriteria.getPacketId())
.build();
// My problem is here - How do I do get the associated Shipment object if my search criteria is a packetId?
if (searchCriteria.getPacketId()!= null) {
return shipmentRepository.findByPackets_Packets_packetId(searchCriteria.getPacketId());
} else {
Example<Shipment> example = Example.of(shipment);
return shipmentRepository.findAll(example);
}
}
And my Repository:
@Repository
public interface ShipmentRepository extends JpaRepository<Shipment, Long> {
List<Shipment> findByPackets_Packets_packetId(String packetId);
}
Since my object Shipment has a list of Packet I cannot simple include it in the Example, or at least I am not sure how.
But I should be able to extract the corresponding Shipment based on a single String packetId, right?
I am getting an Exception:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property parcels found for type Packet! Did you mean 'packetId'? Traversed path: Shipment.packets.
I also tried to define the Query by myself:
@Query("select s from Shipment s left join s.packets p where s.id = p.shipment")
But then I get:
Caused by: org.hibernate.QueryException: could not resolve property: shipment of: com.shipment.persistence.model.Packet
Although shipment is my foreign key.
Any ideas what I am doing wrong? Or what I can maybe improve?