JPA @NamedQuery with bitwise AND (&) as criteria

安稳与你 提交于 2020-06-23 05:04:47

问题


does anyone know how to use bitwise AND (&) as criteria for a JPA NamedQuery without having to use a @NamedNativeQuery?

I'm storing status bits in a field.

I'm using the following defs for an entity of a view:

@NamedQueries({
    @NamedQuery(name="ViewProductsList.findAll", query="SELECT v FROM ViewProductsList v"),
    @NamedQuery(name="ViewProductsList.findFeatured", query="SELECT v FROM ViewProductsList v WHERE v.statusId & 16"),
    @NamedQuery(name="ViewProductsList.findBySubcategory", query="SELECT v ViewProductsList v WHERE v.subcatId IN (:subcatIds)"),
})

The first one works fine, but the second does not like the expression, I get the following:

18:02:13,528 DEBUG [DataNucleus.Query] - JPQL Single-String with "SELECT v FROM ViewProductsList v WHERE v.statusId & 16"
18:02:13,553 DEBUG [DataNucleus.Query] - JPQL Query : Compiling "SELECT v FROM ViewProductsList v WHERE v.statusId & 16"
>>ERROR: 'Portion of expression could not be parsed: & 16'

Using dev MySQL database and Google Cloud SQL in production, so it would have to work on both versions...

Any ideas?

UPDATED QUESTION:

When using a defined @NamedNativeQuery as follows:

@NamedNativeQuery(name = "ViewProductsList.findFeatured", query = "SELECT * FROM view_products_list v")

And calling it as follows:

Query query=em.createNativeQuery("ViewProductsList.findFeatured", ViewProductsList.class);
List<ViewProductsList> list = query.getResultList();

I get the following error:

java.lang.IllegalStateException: You cannot invoke getResultList/getSingleResult when the Query is an UPDATE/DELETE
    at org.datanucleus.api.jpa.JPAQuery.getResultList(JPAQuery.java:161)
    at cultivartehidroponia.ProductsServlet.doGet(ProductsServlet.java:81) ...

I have tried many variations of createNativeQuery examples with no success. Does anybody know of working native query examples using datanucleus?

Again, using a normal @NamedQuery with createNamedQuery works fine!

Thanks in advance!!!


回答1:


Bitwise AND is not part of JPQL. But...

Can be use 2 rules:

  1. division by 2^х will shift the bits right by x (exemple 1011010/1000=1011)
  2. z mod 2 = 1 if right bit is 1 (exemple 1011 mod 2 = 1)

try

SELECT v FROM ViewProductsList v WHERE MOD(v.statusId/16 , 2) = 1



回答2:


'Bitwise AND' is not part of JPQL. Native query is the portable way to go.



来源:https://stackoverflow.com/questions/21246772/jpa-namedquery-with-bitwise-and-as-criteria

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