JPA query many to one association

10,651

Given the following Entities:

@Entity
public class APDU implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    private APDUGroup group;

    //...

}

@Entity
public class APDUGroup implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    //...
}

The following query will return a list of APDUs for a given APDUGroup id:

select a from APDU a where a.group.id = :id

Oh, wait, that's your query :)

Share:
10,651
Random Joe
Author by

Random Joe

Just a curious internet savy Hippopotamus

Updated on June 04, 2022

Comments

  • Random Joe
    Random Joe almost 2 years

    I want to build the following pseudo query

    Select a From APDU a where a.group.id= :id

    group is a field in APDU class of the type APDUGroup.class.

    I just want to get a list of APDUs based on APDUGroup's id.

    How do i do that using a standard JPA query?

    UPDATE

    Yes, I have tried the above query and tried other variations for hours before posting in S/O. Here is the generated SQL for the query above:

    SELECT t1.ID, t1.status, t1.type, t1.modified, t1.response, t1.expectedSize, t1.created, t1.description, t1.sequence, t1.name, t1.command, t1.recurring, t1.auth, t1.createdBy, t1.APDUGroup, t1.modifiedBy FROM APDUGroup t0, APDU t1 WHERE ((t0.ID = ?) AND (t0.ID = t1.APDUGroup))
    

    The query looks okay but nothing get selected from my table. There are at least 100 APDUs with APDUGroup = 1 in my test database.

    I'm using eclipselink as the JPA provider.

  • Random Joe
    Random Joe about 14 years
    OMG!you are right! that is my query :), I tried that before posting here, I didn't get any results at all. Thought maybe there are other ways to do it.
  • Random Joe
    Random Joe about 14 years
    I have found the source of my misery. There is nothing wrong with the query, some codes in the service layer set the associated APDU Groups to null to prevent circular graph relationship when the objects are serialized to XML. Thanks for your help :)
  • Devanshu Mevada
    Devanshu Mevada about 14 years
    @Random Glad you found the (real) problem :)