Archives for: October 2005, 20

Oct 20, 2005 : Hibernate many-to-many relationships and Criteria queries

In hibernate, if you have a many-to-many relationship and you try to query it using a Criteria query you need to add:

criteria.setResultTransformer(Criteria.ROOT_ENTITY);

If you don't, you get a full cartesian join between the primary object and the related objects. So you get all the combinations listed, not just one per object like you'd like.

For example, using annotations I have a class like this:


@Entity(access = AccessType.FIELD)
public class PrintOrder {
	...
	
	@ManyToMany(fetch = FetchType.EAGER)
	@JoinTable(table = @Table(name="tblPrintOrderProcesses"))
	protected List<PaperProcess> paperProcesses;

	...
}

Then the Criteria Query should go something like this:


/** HibernateDaoSupport is a spring class and in this example is only relevant for the getSession() call */
public class MyDAOClass extends HibernateDaoSupport
	public .. some method() {
		Criteria criteria = getSession().createCriteria(PrintOrder.class);
		criteria.setResultTransformer(Criteria.ROOT_ENTITY);
		Property sort_property = Property.forName(sortField);
		Order sort_order;
		if (asc) {
			sort_order = sort_property.asc();
		} else {
			sort_order = sort_property.desc();
		}
		criteria.addOrder(sort_order);
		List list = criteria.list();
	...

So now you get only unique PrintOrders instead of multiple PrintOrders when the order has multiple paperProcesses.

<  October 2005  >
Mon Tue Wed Thu Fri Sat Sun
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31  

Categories


Archives

Misc

Syndicate this blog XML

powered by
b2evolution