随笔-57  评论-170  文章-17  trackbacks-0
  2005年6月3日
      Criteria Query是很好的一种面向对象的查询实现,它提供了一种示例查询的方式。该方式根据已有的对象,查找数据库中属性匹配的其他对象。
      下面是一个场景片断,模糊查找数据库中用户帐号为'test',邮件地址为'georgehill@21cn.com'的实例,忽略大小写。

  public void testCriteriaExampleQuery() throws Exception {
    User user 
= new User();
    user.setAccount(
"test");
    user.setEmail(
"georgehill@21cn.com");
    
    Criteria criteria 
= session.createCriteria(User.class).add(Example.create(user).enableLike(MatchMode.ANYWHERE).ignoreCase());
    List list 
= criteria.list();
    
    
if (list != null{
      
for (int i = 0; i < list.size(); i++{
        System.
out.println(((User) list.get(i)).getAccount());
      }

    }

  }

      示例查询需要生成Example实例,可以通过Example的静态方法create生成。Example类有下面的几个方法指定查询的方式:

excludeZeroes

public Example excludeZeroes()
Exclude zero-valued properties


excludeNone

public Example excludeNone()
Don't exclude null or zero-valued properties


enableLike

public Example enableLike(MatchMode matchMode)
Use the "like" operator for all string-valued properties


enableLike

public Example enableLike()
Use the "like" operator for all string-valued properties


ignoreCase

public Example ignoreCase()
Ignore case for all string-valued properties


excludeProperty

public Example excludeProperty(String name)
Exclude a particular named property



      当用enableLike()方法时,可以通过MatchMode指定匹配的方式。MatchMode提供了四种匹配的方式:

Field Summary
static MatchMode ANYWHERE
          Match the pattern anywhere in the string
static MatchMode END
          Match the end of the string to the pattern
static MatchMode EXACT
          Match the entire string to the pattern
static MatchMode START
          Match the start of the string to the pattern
posted @ 2005-06-03 17:27 小米 阅读(926) | 评论 (3)编辑 收藏