views:

517

answers:

1

I need to make an outer join query that retrieves all of the definitions and any properties they have associated with them that are associated with a certain company.

I have two Hibernate models objects:

class PropertyDefinition {
    @Id
    private Long id;

    @Column
    private String name;

    @OneToMany(mappedBy = "propertyDefinition")
    private Set<Property> properties = new HashSet<Property>();
}

class Property {
   @Id
   private Long id;

   @ManyToOne
   private Integer companyId;

   @ManyToOne
   private PropertyDefinition propertyDefinition;
}

So the query ends up looking like:

from PropertyDefinition as pd left join pd.properties as props with props.companyId = :companyId

So all is peachy so far. The problem I'm having is what sort of structure do I store the returned data in? Hibernate returns a List where [0] is the PropertyDefinition (should never be null) and [1] is the possibly null Property.

My issues:

  • Its obnoxious and not very OO friendly to pass around the List of Object[]s.
  • I can't just hold onto the PropertyDefinition because the list of properties it holds isn't limited to the company.
  • I could create a simple object that holds a reference to the PropertyDefinition and a possibly null Property but its inefficient to have to iterate through the entire List and put each into this new object.

Anyone have a suggestion for a better query or a better mapping structure? I'd really appreciate any assistance.

A: 

Well, normally left join on collection is best handled via fetch which returns a list of container objects with populated collections. However, since you're using with condition, that won't work for you.

If you were to create a simple holder for PropertyDefinition and Property with appropriate public constructor, you could tell Hibernate to return that:

select new Holder(pd, props)
  from PropertyDefinition as pd
  left join pd.properties as props
  with props.companyId = :companyId

It should take care of the issues you've listed; it's not ideal but probably is the best solution available under the circumstances.

ChssPly76
That is exactly what I was looking for! Thanks a lot.
jbarz

related questions