'Bind parameters to the sql request inside a @Subselect annotation in Spring boot?
I'm working on a project in which I need to pass parameters to the @subselect annotation of spring boot (which maps a request to an entity), like the following example:
@Entity
@Immutable
@Subselect("SELECT FROM Employe INNER JOIN Employe_adress ON Employe.id = Employe_adress.eid WHERE Employe_adress.aid=?x")
public class Employe {
...
}
I want to bind an external value to "x" variable. Thank you.
Edit: One method I find is adding a global variable, but "The value for annotation attribute must be a constant expression".
Solution 1:[1]
It can be done with @FilterDef and @Filter: https://www.baeldung.com/hibernate-dynamic-mapping#parameterized-filtering-with-filter
Defining the @Filter
To demonstrate how @Filter works, let's first add the following filter definition to the Employee entity:
@FilterDef(
name = "incomeLevelFilter",
parameters = @ParamDef(name = "incomeLimit", type = "int")
)
@Filter(
name = "incomeLevelFilter",
condition = "grossIncome > :incomeLimit"
)
public class Employee implements Serializable {
The @FilterDef annotation defines the filter name and a set of its parameters that will participate in the query. The type of the parameter is the name of one of the Hibernate types (Type, UserType or CompositeUserType), in our case, an int.
The @FilterDef annotation may be placed either on the type or on package level. Note that it does not specify the filter condition itself (although we could specify the defaultCondition parameter).
This means that we can define the filter (its name and set of parameters) in one place and then define the conditions for the filter in multiple other places differently.
This can be done with the @Filter annotation. In our case, we put it in the same class for simplicity. The syntax of the condition is a raw SQL with parameter names preceded by colons.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | karel |
