views:

229

answers:

1

Hi,

I have a SQL query

SELECT * FROM Thing AS a JOIN Thing_Property AS b ON a.id=b.Thing_ID 
   JOIN Property AS c ON b.properties_ID = c.id 
   JOIN Item AS d ON c.item_ID = d.id 
   ORDER BY a.name, d.name 

and I Eclipselink to create my object model with it. Here is the model:

@SuppressWarnings("serial")
@Entity
public class Thing implements Serializable {
     @Id
     @GeneratedValue(strategy = GenerationType.TABLE)
     private int id;
     private String name;
     @OneToMany(cascade=CascadeType.ALL)
     @PrivateOwned
     private List<Property> properties = new ArrayList<Property>();
     ...
     // getter and setter following here
}
public class Property implements Serializable { 
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private int id;

    @OneToOne
    private Item item;

     private String value;
     ...
     // getter and setter following here
}
public class Item implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private int id;
    private String name;
     ....
     // getter and setter following here    
}
// Code end

but I can not figure out, how to make Eclipselink create the model from that query. Can you help?

+2  A: 

You will need to use the API EntityManager.createNativeQuery(String sqlString, Class resultClass);

entityManager.createNativeQuery("SELECT * FROM Thing AS a JOIN Thing_Property AS b ON a.id=b.Thing_ID JOIN Property AS c ON b.properties_ID = c.id JOIN Item AS d ON c.item_ID = d.id ORDER BY a.name, d.name ", Thing.class);

Gordon Yorke
Thanks! But unfortunately it works but not in the desired way. Instead of having the Property in the list properties I get a 1:1 mapping. Meaning that I should have 10 Thing objects with each 100 Property objects in the properties list, but I have now 1000 Thing objects with each 1 Property objects in the properties list. Eclipselink doesnt do the grouping. Can you help?
Raven
Change your query to use "select distinct a.*" that should reduce the number of Thing objects returned. If you are actually attempting to read all of those related objects as one large query then I recommend using JPQL and EclipseLink's "eclipselink.join-fetch" query hint to fetch join the related objects.Query query = entityManager.createQuery("Select t from Thing T");query.setHint("eclipselink.join-fetch", "t.properties.item");You should be able to add the hints to the native query as well if needed but it is better to use JPQL when you can as it is easier to maintain.
Gordon Yorke