1 Reply Latest reply: Jan 14, 2013 12:03 PM by 984733 RSS

    JPA Criteria Query API and Primary Key Objects

    984733
      I'm trying to use the OpenJPA 2.0 Criteria Query API. I've read through the OpenJPA User's Guide, but there's one subject that I have not found mentioned anywhere. It's how to use a field in a primary key that is an object. For instance:
      @Embeddable
      public class MachinePK implements Serializable {
           private String serial;
           private String type;
      ...
      
      @Entity
      @Table(name="MACHINES")
      public class Machine implements Serializable {
           private MachinePK id;
           private String location;
      ...
      I've seen many examples of how to use a single field in the where clause.
      Root<Machine> machineRoot = criteriaQuery.from(Machine.class);
      Path<String> locPath = machineRoot.get(Machine_.location);
      Predicate predicate = criteriaBuilder.equal(locPath, "BLDG01");
      criteriaQuery.where(predicate);
      ...
      However, what if I want to select on the primary key? Or what if I just want to select on one of the fields in the primary key? I'm assuming I start with this:
              Path<MachinePK> path = machineRoot.get(Machine_.id);
      But I don't know where to go from here.

      Edited by: 981730 on Jan 14, 2013 9:58 AM

      Edited by: 981730 on Jan 14, 2013 9:59 AM
        • 1. Re: JPA Criteria Query API and Primary Key Objects
          984733
          Okay, I figured out how I need to do this:
          Root<Machine> machineRoot = criteriaQuery.from(Machine.class);
          Path<MachinePK> pkPath = machineRoot.get(Machine_.id);
          Path<String> serialPath = pkPath.get(MachinePK_.serial);
          Predicate serialPredicate = criteriaBuilder.equal(serialPath, "SER01");
          criteriaQuery.where(serialPredicate);