Skip to main content

Posts

Showing posts from November, 2010

How to use MatchMode in your JPA/Hibernate Restrictions & Criteria queries

Back in July I blogged about how to do AND/OR type SQL queries using Hibernate AND/OR JPA using disjunctions . If you looked at the example code you will have seen that I was appending "%" as the wildcard operator in my Restrictions . Since then I've used Restrictions a couple more times and wondered if there was a better way of specifying them other than string concatenation. Well there is and it's with the use of the MatchMode class. Rather than this code: import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; Criteria criteria = session.createCriteria(Product.class); criteria.add( Restrictions.disjunction() .add(Restrictions.ilike("code", codeOrName + "%")) .add(Restrictions.ilike("name", "%" + codeOrName + "%")) ); return criteria.list(); You can now write: import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.crite

Accessing & iterating over a Java Map in a JSP page with JSTL

When you are coding JSP pages using JSTL one thing you use a lot is the <c:foreach> tag . This tag a great for iterating over Lists or Sets but what do you do when you want to display the contents of a Map ? Firstly you need to decide how you are going to use the Map. Do you want to access a 'value' stored within the Map based on a known key or iterate over the Map displaying both key and value? Access a Map based on a 'key' This one is pretty straight forward you just need to know the JSTL syntax: ${aMapFullOfKeysAndValues[yourKnownKey]} Two key points: The key is an existing JSTL variable or a quoted string You use square brackets at the end of the Map name Iterate over a Map pulling out the 'key' & 'value' This is a little more complex, note the name of the variable that is filled on each pass through the Map ('entry'): ${entry.key} - ${entry.value} Four key points: The name of the Map is placed as the 'i