Question

Edit: Cleaning up by removing details not relevant to the problem.

The problem. JPA query returns no results.

String qstr = "select o from MyStats o where o.queue_name = :queue"; 
String queue = "3";
em.createQuery(qstr).setParameter("queue", queue);

I thought the problem was either in an incorrect syntax of the JPA query or in incorrect annotation of EmbeddedID. Hence I posted definitions of classes involved but told nothing about database table apart from that it was Oracle.

My test code: Read from DB, take first value and re-use that value in subsequent select query meaning that record exists. Should be there, it was just read, right?

Test

String queue = ""; 
String qstr1 = "select o from MyStats o";
String qstr2 = "select o from MyStats o where o.queue_name = :queue"; 

logger.debug("SQL query: " + qstr1); 
List<MyStats> list = em.createQuery(qstr1).getResultList();
logger.debug("111 Returning results: " + list.size());
for (MyStats s : list) {
    queue = s.getQueue_name();
    logger.debug("Picking queue name: " + queue); 
    break;
}

logger.debug("SQL query: " + qstr2); 
list = em.createQuery(qstr2).setParameter("queue", queue).getResultList();
logger.debug("222 Returning results: " + list.size());

Output:

SQL query: select o from MyStats o
111 Returning results: 166
Picking queue name: 3
SQL query: select o from MyStats o where o.rec_id.queue_name = :queue 
222 Returning results: 0

Class definition

@Entity
public class MyStats {
    private String queue_name;
    private long stats_id;

    ... //getters and setters
}

A query without WHERE clause works correctly so as a query with a member of MyStats class.

em.createQuery("select o from MyStats o where o.stats_id = :sid").setParameter("sid", 179046583493L);

I am using Oracle 10 database, Java EE 5 SDK, Glassfish 2.1.

Was it helpful?

Solution

The problem appeared to be with the mapping of Java String type to database column CHAR type.

Database table queue_name column is defined as CHAR(20), while Java type is String.

There are few options to fix it

  1. Replace database column CHAR type with VARCHAR
  2. Pad query parameter value with spaces for every request
  3. Use LIKE condition instead of equals = and add % to the end of parameter value
  4. Speculative: Use cast

(1) Acceptable if you have control over the database table

(2) Works for the given select statement, possibly breaks for JOINs

(3) May fail to do the trick. LIKE 'a%' returns not only 'a ' but 'aa ', 'abc ', and so on

(4) This is not completely clear to me. I am not sure if it is possible to adopt:

em.createNativeQuery("select cast(queue_name as CHAR(20)) from ..."); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top