Search code examples
javajpaopenjpa

JPA query, oneToMany or manyToOne, should both work?


I am porting some code from an old OpenJPA implementation to a more recent one, specifically to

OpenJPA 2.1.0-SNAPSHOTversion id: openjpa-2.1.0-SNAPSHOT-r422266:990238

My previously working query failed in this new environment (details of the exact failure later) but recasting the query worked just fine. The difference lies in which side of a one-to-many query I start at. My question is in two parts:

  1. Is there a "correct" side from which to start such a query? Would we expect both queries to work?
  2. If we would expect both to work, can we explain the failure I'm seeing.

For the sake of brevity the classes here are rather cut down. One side of the relation:

@Entity
@Table(name="CWS_MDS")
public class CwsMd implements Serializable {

    @Id
    Column(name="RSM_ID", unique=true, nullable=false, length=128)
    private String rsmId;

    // ... many elisions ... 

   //bi-directional many-to-one association to CwsPubOperationRef
   @OneToMany(mappedBy="cwsMd")
   private Set<CwsPubOperationRef> cwsPubOperationRefs;

}

the other side

   @Entity
   @Table(name="CWS_PUB_OPERATION_REF")
   public class CwsPubOperationRef implements Serializable {

  @EmbeddedId
  private CwsPubOperationRefPK id;

 //bi-directional many-to-one association to CwsMd
    @ManyToOne
  @JoinColumn(name="RSM_ID", nullable=false, insertable=false, updatable=false)
  private CwsMd cwsMd;

    // ... more elisions ...
    }

The query that works:

 <named-query name="good"> <query>   
      SELECT opref FROM CwsPubOperationRef opref
            JOIN opref.cwsMd rsm
            WHERE rsm.rsmId = :rsmId                                                      
  </query>
 </named-query>

The one that does not

  <named-query name="bad"> <query>   
         SELECT opref FROM CwsMd rsm
            JOIN rsm.cwsPubOperationRefs opref
            WHERE rsm.rsmId = :rsmId
     </query> </named-query>

The error that I get is

 org.apache.openjpa.persistence.PersistenceException: [jcc][t4][10120][10898][3.57.82]   
 Invalid operation: result set is closed. ERRORCODE=-4470, SQLSTATE=null

I'm running on WebSphere 8.0, on Windows, using DB2 as the database.


Solution

  • Second query is incorrect, because identification variable opref refers to collection (rsm.cwsPubOperationRefs is collection ) and not to single value.

    In JPA 2.0 specification this is told with following words:

    It is illegal to use a collection_valued_path_expression other than in the FROM clause of a query except in an empty_collection_comparison_expression, in a collection_member_expression, or as an argument to the SIZE operator.

    First query is perfectly fine - CwsPubOperationRef because identification variable refers to single value.