Question

I'm trying to come up with a criteria that would check whether or not a certain string is one of a number of possible patterns.

e.g. myField should not conform to any of the following patterns: pattern1%, pattern2%, pattern3%

If I were to do this one at a time, the restriction would look something like

criteria.add( Restrictions.not(Restrictions.in("myField", "pattern1%")) )

for each of the patterns. Since there are several, I thought of trying out the disjunction restriction from hibernate like the answer found here. For example's sake, let's just say I'm not using patterns and am equating to a series of fixed strings. So I was hoping for something like:

criteria.add(
   Restrictions.disjunction()
      .add(Restrictions.like("myField", "str1"))
      .add(Restrictions.like("myField", "str2"))
)

But, for some reason, this doesn't work. When I changed it to:

criteria.add( 
   Restrictions.disjunction()
      .add(Restrictions.like("myField", "str1"))
      .add(Restrictions.like("anotherField", "str2"))
)

it does, so I wasn't sure if it's because disjunction won't permit multiple conditions to the same field. However, samples here in section 15.2 show otherwise with the "age" field.

Hence, at the moment, I'm forced to use

criteria.add(
   Restrictions.in("myField", new String[] {"str1", "str2"})
)

which only solves half my problem since I need patterns to be in there somewhere.

So my question is, is it possible to use disjunction or in to check if a string matches any of the patterns that may be defined? If so, how? Or is there a better way?

Thanks!

Was it helpful?

Solution

You can try something like this:

criteria.add(Restrictions.disjunction().add(
                Restrictions.or(Restrictions.like("myField", "str1"),
                        Restrictions.like("myField", "str1"))));

Or if there is some pattern you are looking for then this should work:

criteria.add(Restrictions.disjunction().add(
                    Restrictions.or(Restrictions.like("myField", "%"+"str1"),
                            Restrictions.like("myField", "str1"+"%"))));

Hope this helps..!!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top