I have a Transaction
entity with a one-to-many relationship to Detail
entities. When I try to fetch Transaction
entities using a method that utilizes Spring Data JPA’s Specification
and Pageable
, I’m only getting the Detail
records that match the criteria, rather than all of them.
Here’s how I’m fetching the Transaction
entities:
@EntityGraph(value = "Transaction.details", attributePaths = ["details"])
fun findAll(search: Specification<Transaction>, pageable: Pageable): Page<Transaction>
And here’s how I’m forming my Specification
to filter based on Detail
attributes:
val detailsJoin = root.get<Detail>("details")
predicates.add(builder.equal(detailsJoin.get<String>("invoiceId"), id))
My entity mappings are as follows:
Transaction Entity:
@Entity
@NamedEntityGraph(
name = "Transaction.details",
attributeNodes = [NamedAttributeNode("details")]
)
@Table(name = "transaction_records")
@IdClass(TransactionId::class)
data class Transaction(
@Id @Column(name = "part_id") var partId: Int,
@Id @Column(name = "tx_id") var txId: String,
@OneToMany(
mappedBy = "transaction",
fetch = FetchType.LAZY,
cascade = [CascadeType.PERSIST, CascadeType.MERGE]
)
var details: List<Detail> = ArrayList()
) : PersistableEntity<TransactionId>()
Detail Entity:
@Entity
@Table(name = "detail_records")
@IdClass(DetailId::class)
data class Detail(
@Id @Column(name = "part_id") var partId: Int,
@Id @Column(name = "detail_id") var detailId: String,
@Id @Column(name = "tx_id") var txId: String,
@Column(name = "invoice_id") var invoiceId: String,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns(
JoinColumn(
name = "part_id",
referencedColumnName = "part_id",
insertable = false,
updatable = false
),
JoinColumn(
name = "tx_id",
referencedColumnName = "tx_id",
insertable = false,
updatable = false
)
)
var transaction: Transaction? = null
) : PersistableEntity<DetailId>()
I expect to retrieve all Detail
records associated with each Transaction
, but I’m only getting the Detail
records that match the criteria specified in my Specification
. How can I modify my setup to ensure that all associated Detail
records are fetched when querying Transaction
entities?