Wednesday, November 29, 2006

getting your data

People learning ofbiz will probably first be looking for equivalents to the SQL select statements or hibernate calls they are used to. The GenericDelegator object does this. Reading this post requires your understanding that calls to delegator aren't really like select statements at all because these methods return a List of objects and not a cursor. and they aren't like hibernate calls either, because they don't return a List of the specific object type, but a List of GenericValue objects.

select * from table : you are looking for delegator.findAll()
List peopleList = delegator.findAll("PicnicPeople"); will get every record in the PicnicPeople entity. It will come to you as a List of GenericValue objects.

select * from table where... : When you want to limit the records returned, delegator.findByAnd() is what you want. findByAnd takes a Map (or List) of the field names and values you wish to add to the where clause. This is kind of nice because you don't have to worry about constructing Where... AND.... AND.... clauses. There is a utility called UtilMisc.toMap() to construct this map that you will see used a lot.
Map fieldMap = UtilMisc.toMap("name","Fred");
List peopleNamedFred = delegator.findByAnd("PicnicPeople", fieldMap);

select * from table1, table2 where = : outer joins can be accomplished by delegator.getRelated()
if you already have a peopleList populated from the previous example,
aPerson = (GenericValue)peopleList.get(1);
List peopleDateList = delegator.getRelated("PicnicDates",aPerson);
would get back a List containing all the picnic dates that aPerson.
to get the entire list of dates for an entire List of people, you would do a loop through peopleList and perform delegator.getRelated(PicnicDates, (GenericValue)peopleList.get(x)) for each entry in the list. There are other ways to do joins: dynamic views and entity views, but I'm just talking about delegator today.

select * from table1 where name LIKE 'Amy%' wild card queries can be used with delegator.findByLike() as in :
delegator.findByLike(PicnicPeople", UtilMisc.toMap("name","Amy%"));

No comments: