I have to get all registers in my DB (PostgreSQL) with case-insesitive. I have tried with criteria but the ignoreCase() is not working for me (I'm using Hibernate 3.6).
criteria.add(Restrictions.eq(TABLECODEID, tableCodeID).ignoreCase());
I have also tried to use the ilike method but still doesn't work.
criteria.add(Restrictions.ilike(TABLECODEID, tableCodeID));
And this version too:
criteria.add(Restrictions.ilike(TABLECODEID, tableCodeID, MatchMode.ANYWHERE));
So now I'm getting this error when I try to create a query in Hibernate with HQL:
unexpected token: lower near line 1, column 81
My code looks like this:
StringBuffer queryString = new StringBuffer()
.append("from ListItem li ")
.append("where lower(li.tableCodeId) like :tableCodeId");
Query query = session.createQuery(queryString.toString());
query.setParameter("tableCodeId", tableCodeID.toLowerCase());
List<ListItem> listItemListAux = query.list();
What am I doing wrong?
You should resolve in this way, the MatchMode.ANYWHERE will do the trick:
criteria.add(Restrictions.ilike(TABLECODEID, tableCodeID, MatchMode.ANYWHERE));
At the end I used HQL and the problem was I was attacking the entity in the lower(li.tableCodeId) function, I had to use the DB column name lower(tablecodeid)
Related
I am using EntityManager in spring boot app to get result from this query
select (c.data::jsonb)->>'employee_Id' as empId from employee e where e.dept ='employee' and (e.data::jsonb)->>'section_id' = '1235'
Its giving me correct output in PgAdmin but in java code
List resultList = em.createNativeQuery(str).setParameter(1, sectionId ).getResultList();
Giving error ERROR: syntax error at or near ":" its breaking at data::jsonb .How do handle this using EntityManager.
You need to CAST like CAST(c.data as jsonb)->>'product_id' from string to JSONB. However i would highly suggest that you don't use TEXT for your JSON type data.
ALTER TABLE employee ALTER COLUMN data TYPE JSON USING data::JSON;
`
this is the DAO method i have to retrieve the list of students from DB and on RunTime it says -
org.postgresql.util.PSQLException: ERROR: syntax error at or near ")"
which is driving me crazy. Can anyone please tell me what i might have missed?
public List<Student> getStudentsByIds(List<Integer> studentIds) {
Session session = SessionFactoryUtils.getSession(getSessionFactory(), true);
SQLQuery query = session.createSQLQuery("SELECT * FROM students s WHERE s.id IN (:studentIds)");
query.setParameterList("studentIds", studentIds);
return query.list();
}
Probably studentIds is an empty list and postgres does not accept
empty IN clause in generated code
select
...
where
students.id in (
)
Had this issue recently. So as I got from docs psql can't handle empty lists in IN/NOT IN (:someEmptyList) statements cause criteriaBuilder adds empty curly braces into final sql query: (in ())
Imho the easiest solution will be just to check for empty list and return empty result list back.
Or use more advanced tools if u have complex query and u really need it => https://marcelothebuilder.github.io/java/jpa/2017/09/11/jpa-post.html
I have this query:
Field<String> yearMonth = DSL.field("FORMATDATETIME({0}, 'yyyy-MM')",
String.class, LICENZE.CREATION_DATE).as("anno_mese");
List<Record3<Integer, String, String>> records =
create.select(DSL.count().as("num_licenze"), LICENZE.EDIZIONE, yearMonth).
from(LICENZE).
groupBy(LICENZE.EDIZIONE, yearMonth).
orderBy(yearMonth).
fetch();
this query generates:
select
count(*) "num_licenze",
"PUBLIC"."LICENZE"."EDIZIONE",
FORMATDATETIME("PUBLIC"."LICENZE"."CREATION_DATE", 'yyyy-MM') "anno_mese"
from "PUBLIC"."LICENZE"
group by
"PUBLIC"."LICENZE"."EDIZIONE",
"anno_mese"
order by "anno_mese" asc
executing it i get: Column "anno_mese" not found; SQL statement
Testing the generated query and removing the quotes from anno_mese in every parts of the query make the query works instead.
Is my query wrong or am I using jooq in the wrong way?
The alias in this query is not so important, I can run the query without using it too but just to understand how it works.
I am using h2 as database.
Thanks for the help
I suspect this is a bug in H2, which I've reported here, because the query looks fine to me. Here are some workarounds that you can do from the jOOQ side:
Don't reference the "anno_mese" column by name
While SQL is a bit repetitive otherwise, you won't notice the difference with jOOQ. I simply moved the as("anno_mese") method call into the SELECT clause. You don't really need it in the GROUP BY and ORDER BY clauses.
Field<String> yearMonth = DSL.field("FORMATDATETIME({0}, 'yyyy-MM')",
String.class, LICENZE.CREATION_DATE);
List<Record3<Integer, String, String>> records =
create.select(DSL.count().as("num_licenze"),
LICENZE.EDIZIONE,
yearMonth.as("anno_mese")).
from(LICENZE).
groupBy(LICENZE.EDIZIONE, yearMonth).
orderBy(yearMonth).
fetch();
Disable quoting in jOOQ generated queries
You can use jOOQ's Settings to prevent schema / table / column names from being quoted. Example:
DSLContext create = DSL.using(connection, SQLDialect.H2,
new Settings().withRenderNameStyle(RenderNameStyle.AS_IS);
Use upper case column names
This will probably work: DSL.field(...).as("ANNO_MESE")
In SQL Server i am using this query
select *
from Unit c
ORDER BY CONVERT(INT, LEFT(name, PATINDEX('%[^0-9]%', name + 'z')-1)) desc;
I want this query to use in Hibernate. when I use this in Hibernate I got error
java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException:unexpected token: LEFT near line 1, column 122
[SELECT c FROM models.entities.UnitEntity c WHERE c.expSetId = :expSetId AND isWaitArea=:isWaitArea ORDER BY CONVERT(INT, LEFT(name, PATINDEX('%[^0-9]%', name + 'z')-1)) asc]
some of that is not in the hibernate dialect, you can change left with substring, convert with cast. and as for patindex i couldn't find the substitution. you either can add pathindex to the constructor of the dialect that you use
registerFunction( "patindex", new StandardSQLFunction("patindex") );
or create patindex() to a stored procedure.
then you can use something like this:
from Unit c order by cast(substring(name, 0, PATINDEX('%[^0-9]%', name + 'z')-1) as integer);
or you can use locate() instead of patindex(), but i think it doesn't support regular expression.
I am pretty sure that you can use SQL query with hibernate as well. When you create your hibernate session, you can use something like
session.createSQLQuery("Your Query Here")
Hope this helps.
I'm using Hibernate for database access. I'm using the following query in my code to fetch the data I need:
SELECT proasset
FROM com.company.claims.participant.AbstractBeneficiary bene
JOIN bene.approvals approval
JOIN bene.proassetkey proasset
join proasset.relatedparties proassetparties
WHERE approval.user_dt > :currentDate
AND approval.user_type = :userType
I'm using it as query in the following:
Query q = this.getSessionFactory().getCurrentSession().createSQLQuery(query.toString())
q.setDate("currentDate", new Date());
q.setString("userType", APPROVER_USER_TYPE);
List<ProAsset> proassets = q.list();
However, I encounter the following when trying to run it:
SQL Error: 933, SQLState: 42000
ORA-00933: SQL command not properly ended
If it matters, the query is being constructed using a StringBuilder and it uses \n to break the lines
Any thoughts on the problem?
It looks like you are trying to mix ORM with a native (plain old SQL) query.
createSQLQuery requires native SQL. You are using classes instead of table names. Try a read of this:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html
In short you need to write a query like:
select fu
from bar
where situation = 'snafu'
Perhaps you are really wanting to write a namedQuery? They use ORM syntax where you join entities as it seems you are doing in your example.
Check these examples out:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#querysql-namedqueries
Correct the syntax by removing the inappropriate clauses. It may be possible to duplicate the removed clause with another SQL statement. For example, to order the rows of a view, do so when querying the view and not when creating it. This error can also occur in SQL*Forms applications if a continuation line is indented. Check for indented lines and delete these spaces.
Alright, so I used createSQLQuery() instead of createQuery() and I was using the column names instead of the variable names.
Here's what my code looks like now:
StringBuilder query = new StringBuilder();
query.append("SELECT proasset\n" +
"FROM com.avivausa.claims.participant.AbstractBeneficiary bene\n" +
"JOIN bene.approvals approval\n" +
"JOIN bene.proAsset proasset\n" +
"join proasset.additionalParties proassetparties\n" +
"WHERE approval.userDate < current_date()\n");
query.append("AND approval.userType = ").append(UserAuditType.APPROVER);
Query q = this.getSessionFactory().getCurrentSession().createQuery(query.toString());
List<ProAsset> proassets = q.list();
Obviously I made some refactoring changes too, but the main changes were what I stated above. Thank you for your responses though!