I have a complex query e.g. search employees with name, age, address, etc
I would like to append a WHERE clause if a parameter IS NOT NULL.
for example (pseudo code):
if (age != null) // then append age to the where clause
whereClause += whereClause + AND age = :age"
I would like to use a NamedQuery in an XML file, but a NamedQuery does not support conditional where like myBatis
Can anyone help me resolve this problem?
For this simple case/condition you can solve the problem with a NamedQuery:
SELECT e FROM Entity e WHERE (:age IS NULL) OR (:age IS NOT NULL and e.age=:age)
If you want more complex queries (e.g. where you sort dynamically by the column), I would use Criteria API.
Related
i am trying to write the below query into spring boot jpql (postgresql db)
first_name
FROM
employees
WHERE
first_name LIKE concat(concat('%',nvl(:key,first_name) ),'%'); --This is oracle style query
Iam trying to write the same logic in JPQL(am new to JPA and JPL , but i know this simple logic ,we can achieve using the implementation less queires , but the above mentioned is a part of a bigger query).
I tried like below. But stuck actually.
#Query("select pe.packageName from PackageEntity pe where " +
"lower(pe.packageName) like " +
"case when :packageName is null then lower(pe.packageName) else concat('%',lower(:packageName),'%') end " )
List<String> getValues( #Param("packageName") String roomIDList);
Error Message is below
org.postgresql.util.PSQLException: ERROR: function lower(bytea) does not exist Hint: No function matches the given name and argument types. You might need to add explicit type casts. Position: 190
Honestly , i've tried every possible solution , i can think of. found same error in stackoverflow , but there solution doesn't match, I really want to send the null values in the query , if the input is null then need to ignore the validation, for example if the input parameter is null, then i want to completely ignore the validation.
solution :-
#Query("select pe.packageName from PackageEntity pe where " +
":packageName is null or lower(pe.packageName) like
concat('%',lower(:packageName),'%')" )
The above workaround worked actually.
But I implemented like, In cotroller code
if (search.getPackageName() == null) {
LOGGGER.info("Input Name is NULL");
search.setPackageName("==!##$%^&*()!##$%^&*()==");
LOGGGER.info("Input Name is set to Default " + search.getPackageName());
}
searchValue = repoPackage.getPackageAll(search.getPackageName());
in repo, where condition is like below - Not sure , if the solution is the best, but it worked. Like this I avoided sending any null value to jpa.
where
(('==!##$%^&*()!##$%^&*()==' = :packageName)
or lower(pd.package_name) like concat('%', lower(:packageName), '%'))
Technology: EF 6.1.3, Database First Approach and SQL Server.
Issue: I'm facing an issue with the following Linq Query,
EmployeeEntities db = new EmployeeEntities();
IQueryable<Model.Employee> employees = from e in db.Employee
where e.EmployeeName == null
select e;
I'm trying to get employees whose EmployeeName is Null but I'm not getting any records, whereas when I query in the database (SQL Server), I'm getting the results properly.
I suspect the linq query is not converting where clause as EmployeeName IS NULL but it simply converts like EmployeeName == null.
Please let me know how to fix this issue..
Thanks,
Prakash.
You need to call ToList() to materialize the query. EF will definitely convert to the proper operator in SQL.
So the code becomes:
List<Model.Employee> employees = (from e in db.Employee
where e.EmployeeName == null
select e).ToList();
In mysql, we can return specific result like as:
select name,lastName from users where id=1;
how use the same request in doctrine2?
I khnow that we can use
$query=$this->_em->createQuery('select a.name, a.lastName from ...:Users a'); but i search some methods to user it without a.name
for examlpe
$query=$this->_em->createQuery('select name, lastName from ...:Users '); is correct?
it's possible to return just the name and the lastname from a table without the prefix a?
If you want to select some specific fields from the database you need to use the partial keyword.
Taken from the doctrine partial object documentation your query should look like:
$query=$this->_em->createQuery('SELECT partial u.{name, lastName} from Users u');
This will return an array of partially loaded User objects.
I am trying to use the Criteria API instead of constructing queries as JPQL Strings as the Criteria API seems much better suited for this. However, I am having a few problems understanding how to construct the two following statements.
SELECT e
FROM Subject e
WHERE e.company = :c1
OR e.company = :c2
OR e.company = :c3
In this case I need to iterate over an unknown number of values (c1, c2, c3 etc.) to match to the same attribute.
SELECT e
FROM Subject e
WHERE e.company
LIKE :c1
OR e.account
LIKE :c1
OR e.email
LIKE :c1
In this case I need to pass in a single value (c1) and have a 'LIKE' comparison done on a specific range of attributes.
My current pattern looks something like this:
// Criteria
CriteriaBuilder builder = subjectDAO.criteriaBuilder();
CriteriaQuery<Subject> query = builder.createQuery(Subject.class);
// Root
Root<Subject> subject = query.from(Subject.class);
List<Predicate> predicates = new ArrayList();
for (String property : map.keySet()) {
String value = (String) coreFilter.get(map);
predicates.add(????? This is where I come unstuck ?????);
}
// pass all the predicates into the query
query.where(predicates.toArray(new Predicate[predicates.size()]));
NB. I don't have any problems constructing the Query object or specifying the Root or Joins. I am just having problems with the specificity of the above queries. For the sake of clarity just assume that all the attributes are String and don't require any joins.
The expression CriteriaQuery<T> where(Predicate... restrictions), as you can see in the javadoc,
Modify the query to restrict the query result according to the conjunction of the specified restriction predicates.
So, it makes the conjunction of the predicates in the list, i.e. it concatenates them with AND expressions. In order to concatenate them with OR expression, simply use CriteriaBuilder#or(Predicate... restrictions)
query.where(builder.or(predicates.toArray(new Predicate[] {})));
I'm new to Entity Framework. I have a database query which I need to convert to Entity Framework. how to write the query in LinQ to Enity
Can someone help me on that?
SELECT
FLD1,
FLD2,
SUM(FLD3),
(TO_CHAR(FLD4,'MM/DD/YYYY'))
FROM
TABLE1
WHERE
(FLD2=XXX ) AND
(FLD3 BETWEEN TO_DATE(VARDATE,'MMDDYYYY') AND TO_DATE(VARDATE1,'MMDDYYYY'))
GROUP BY
FLD1,
FLD2,
FLD4
Well...info is sparse and you filled it with a lot of different cases something like this would do.
_context.SomeObject
.Where(x=>x.SomeField == "SomeValue" && x.SomeField > 5 && x.SomeField < 10)
.Select(x=>new { x.SomeField1, x.SomeField2, x.SomeField2, SomeField4 = x.SomeChildCollection.Sum(y=>y.SomeChildvalue)
.GroupBy(x=>new {x.SomeField1, x.SomeField2, x.SomeField3})
.ToList()
This would result in a group where the key was an object with the values SomeField1, SomeField2, SomeField3, and the object would be the an anonymous projection with the 4 properties in the Select.
In some kinds of comparisions regarding dates you might need to use EntityFunctions.