Search code examples
javajpajpql

How do I query an composed Object in JPA?


I want to now if can JPQL retrieve the composed object. ObjectA has ObjectB (Aggregation). Can I query ObjectB where there is not link with ObjectA. NAtive Query would be like this:

SELECT * FROM OBJECTB WHERE  ID_OBJECTA = NULL

Sometimes JPA creates an associative entity, but I assumed here just added ID_OBJECTA as the reference to his aggregater.

Thanks for your help.

Class ClassA{
public ClassB b;
}

ClassB{
public String data;

}

I know I can query like this:

Select a from ClassA a join a.b bb//Given a retrieve b

I want to do this:

Select b from ClassB b join ...// ClassB doenst have an a Attribute

How can i query ClassA from ClassB


Solution

  • What you want is a bi-directional One-to-One association. You have two options in this case Lazily or Eagerly loaded. Neither require an explicit join in your JQL unless you want to override lazy loading with eager loading. This is of course predicated on the fact that your annotations/xml defining the relationship between these objects is setup correctly.

    You will need a property in ClassB for type ClassA to persist changes in ClassB's relationship independent of ClassA. This property will also allow child queries on ClassB to populate the parent ClassA member with data(eager) or query stubs(lazy)

    public ClassA{
       ClassB Child;
    }
    
    public ClassB{
       ClassA parent;
       String data;
    }
    

    Check out this wiki books entry it walks you through setting this up. One To One It oulines a very similiar scenario in dealing with a Person with an Address and laying how to get the person by querying the Address.

    Note: I just read that you are trying to do this without an association. Like other posters have noted its trivial to add this relationship, If its lazy it adds almost no overhead. The only reason I can think of not to do this is some misguided attempt to avoid polluting classB with references to ClassA. Remember "Worse Is Better" Simplicity -> Correctness --> Consistency -> Completeness. Do it the simplest way that solves you're problem and no simpler.