I have an Order entity (that, well, represnts an order), and each order has a set of DeliveryDates. I'm trying to implement a search function and show the results in a JFace TableVie开发者_Python百科wer.
I want that for every order that has more than one delivery date, it should be duplicated in the table, but the DeliveryDate column would display the specific delivery date for this instance.
This query is easily done in SQL using a simple join, and the rows are duplicated with a different date for every row. Since I'm doing a search feature, I'm building the query in steps (depending on what search parameters the user had chosen), so building a query using Criteria is very useful. The problem is, that the result list I get is duplicated (which is OK), but every entity simply contains the same set of DeliveryDates - so I can't print a different date for different rows of the same Order.
Is there any way to do this using Critera? And if not, how can I do it?
Edit: Edit: For example, this HQL query seems to do something similar: "select dd.deliveryDate, od from Order as od left join od.deliveryDates dd"
Answer: I have found a solution:
Criteria crit = session.createCriteria(Order.class)
.createAlias("deliveryDates", "dd")
.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
I gave the deliveryDates collection an alias, and used a ResultTransformer to return results in a Map. The list of the search results will contain maps that have two keys, "this" (aka Criteria.ROOT_ALIAS) and "dd". This will give me the row duplication that I wanted, and now I can grab the corresponding objects like this:
Map map = (Map) element;
Order ord = (Order) map.get(Criteria.ROOT_ALIAS);
DeliveryDate dd = (DeliveryDate) map.get("dd");
the reason for the duplicate entries (with same data) is that the resulting rows (duplicate ones) have the same primary key & are treated the same by hibernate..
as a solution you need to ensure that the PK is computed differently for each of the entries (try using projections here).
also HQL might be an easier choice (i'd usually prefer HQL in scenarios like this).
Better solution: if you can convert the query (at least a part of it) into a view & fetch data from it then most of the issues will be solved & it will be a better design.
Another approach to achieve what you want in one to many
scenario is building criteria on 'many' end of the relationship.
Criteria crit = session.createCriteria(DeliveryDate.class);
...
DeliveryDate dd = (DeliveryDate) element;
Order ord = dd.getOrder();
精彩评论