Hibernate native query optional parameter throws 'operator does not exist: bigint = bytea'

南楼画角 提交于 2021-01-27 06:31:37

问题


I have a query as follows:

SELECT id FROM table1 WHERE (:param IS NULL OR id_or_smth = :param)

The param parameter is optional, therefore it can be null

  1. I createed a javax.persistance.Query
  2. To which I then setParameter("param", null)
  3. And when I called getResultList() I got the following error:

Caused by: org.hibernate.exception.SQLGrammarException: ERROR: operator does not exist: bigint = bytea

how can i handle this?


回答1:


HQL and Criteria can only work when you specify an actual Entity property/Table column so this doesn't work:

:param IS NULL

If id_or_smth is a Table1 column, then this is how your query should look like:

Query q = entityManager.createNativeQuery("SELECT id FROM table1 WHERE id_or_smth IS NULL or id_or_smth = :param");
q.setParameter("param", paramValye);
q.getResultList();

And paramValue must not be null.

In SQL you must always use IS NULL/IS NOT NULL, because a query like this:

SELECT id FROM table1 WHERE id_or_smth = NULL

will always return an empty result, even if there are rows satisfying id_or_smth IS NULL




回答2:


Maybe you could use criteria queries instead:

Criteria crit = sess.createCriteria(Table1.class);
crit.setProjection(Restrictions.id());
if (param != null) crit.add(Restrictions.eq("id_or_smth", param));

List result = crit.list();


来源:https://stackoverflow.com/questions/25360336/hibernate-native-query-optional-parameter-throws-operator-does-not-exist-bigin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!