Intro:
I’m using QueryDSL with Hibernate in a Spring Boot project. I’ve noticed a difference in the way @SQLRestriction
is applied when using join(a, b)
versus join(b).on()
. Specifically, when using join(a, b)
, the @SQLRestriction
on both entities a
and b
is applied, but when using join(b).on()
, only the @SQLRestriction
on entity a
is applied.
Example Entities:
@Entity
@SQLRestriction("deleteTime is null")
data class Order(
@Id
val id: Long,
@ManyToOne
@JoinColumn(name = "customer_id")
val customer: Customer,
val deleteTime: LocalDateTime?
)
@Entity
@SQLRestriction("deleteTime is null")
data class Customer(
@Id
val id: Long,
val name: String,
val deleteTime: LocalDateTime?
)
QueryDSL Example:
Using join(a, b):
val query = JPAQuery<Order>(entityManager)
val order = QOrder.order
val customer = QCustomer.customer
query.from(order)
.join(order.customer, customer)
.where(customer.name.eq("John Doe"))
.fetch()
Resulting Native Query:
SELECT o.*
FROM orders o
JOIN customers c ON o.customer_id = c.id AND c.delete_time IS NULL
WHERE o.delete_time IS NULL AND c.name = 'John Doe';
Using join(b).on():
val query = JPAQuery<Order>(entityManager)
val order = QOrder.order
val customer = QCustomer.customer
query.from(order)
.join(customer).on(order.customer.id.eq(customer.id))
.where(customer.name.eq("John Doe"))
.fetch()
Resulting Native Query:
SELECT o.*
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.delete_time IS NULL AND c.name = 'John Doe';
Note: The resulting native queries are not from actual QueryDSL execution but are written to illustrate the behavior I observed.
Issue:
When using join(a, b), the @SQLRestriction on both Order and Customer entities is applied correctly. However, when using join(b).on(), the @SQLRestriction on the Customer entity is not applied automatically. Interestingly, the @SQLRestriction on the Order entity is still applied correctly in the from clause.
Question:
Why does @SQLRestriction behave differently when using join(b).on() compared to join(a, b)? Is there a way to ensure that @SQLRestriction is applied to both entities when using join(b).on()?
Any insights or documentation references that explain this behavior would be greatly appreciated.
• In a real service operation, when joining two tables a and b, I noticed that the @SQLRestriction was not applied in the query log.
• Initially, there was no relationship between the two tables.
• I observed that the code working correctly in another project had the common point of having relationships between tables.
• I established the relationship and used join(b).on(), but still only the @SQLRestriction on entity a was applied.
• When using join(a, b), both restrictions were applied as expected.
Goose is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.