开发者

Hibernate restrictions (And / Or)

small questions about Restrictions.

i have query like this :

Where  A in(1,6) and (B not like 'Value%' or B not like 'V开发者_开发知识库alueII%')

the problem is the field B not contains a fixed value, can be one or more.

Please, (N)Hibernate experts - help me with this, I cant find a working solution. Any help is greatly appreciated!


You can use disjunctions to handle the OR cases, as such:

IList results = session.CreateCriteria(typeof(MyType))
    .Add(Restrictions.In("A", new [] {1, 6}))
    .Add(Restrictions.Disjunction()
        .Add.Restrictions.Not(Restrictions.Like("B", "Value%"))
        .Add.Restrictions.Not(Restrictions.Like("B", "ValueII%")))
    .List<MyType>();

If you need to handle the disjunction conditions in a for loop (per your follow-up), you can use code like this:

ICriteria query = session.CreateCriteria(typeof(MyType));
query.Add(Restrictions.In("A", new [] {1, 6}))

Disjunction disjunction = Restrictions.Disjunction();
foreach (var value in values) {
    disjunction.Add(Restrictions.Not(Restrictions.Like(value, "Value%")));
    disjunction.Add(Restrictions.Not(Restrictions.Like(value, "ValueII%")));
}
query.Add(disjunction);

IList results = query.List<MyType>();

That being said, I think there may be a flaw in your logic. If you are testing these values to "not match one pattern OR not match another pattern", then the condition will always evaluate to true (unless the patterns are the same). Are you sure you want to be using ORs here?


the problem is that I don't know exact how many restrictions i have and i need to use FOR in disjunction.

Something like that:

IList results = session.CreateCriteria(typeof(MyType))
.Add(Restrictions.In("A", new [] {1, 6}))
.Add(Restrictions.Disjunction());
 for(int i = 0, i < value.Lenght;i++){
    .Add.Restrictions.Not(Restrictions.Like("B", "Value%"));
    .Add.Restrictions.Not(Restrictions.Like("B", "ValueII%"));
 }
.List<MyType>();

thanks for you help

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜