hibernate模糊查询

阅读更多

字段为varchar,也就是string的模糊查询方法如下:

 

 String work = wsform.getWork();
 criteria.add(Restrictions.like("work",work,MatchMode.ANYWHERE));

  

 

而long 型的需要用下面这种方法:

 criteria.add(Restrictions.sqlRestriction("{alias}.WORK LIKE (?)","%"+work +"%",Hibernate.STRING));
 

 

用上面这句就看到结果了, 其中WORK是表里的字段名,对象里的名为work, 但这里不能用对象里的名,否则后台翻译成sql语句的时候,字段名不会变成WORK,造成bug.

  

    Hibernate.STRING已经过时,替换为StandardBasicTypes.STRING

 

 

   /* 根据属性名获得对应字段名
  */
public String getColumnName(Class clazz, String propertyName) {
   List resultList = new ArrayList();
   SessionFactory factory = getHibernateTemplate().getSessionFactory();
   AbstractEntityPersister classMetadata = (SingleTableEntityPersister) factory.getClassMetadata  (clazz);
   boolean isCollection = classMetadata.getClassMetadata() .getPropertyType(propertyName).isCollectionType();
   if (!isCollection) {
    for (String columnName : classMetadata
      .getPropertyColumnNames(propertyName)) {
     resultList.add(columnName);
    }
   }
   if (resultList != null && resultList.size() >= 1) {
    return resultList.get(0);
   }
   return null;
}
 
 
/** 
* @param obj 属性所在对象 
* @param PropertyName 属性变量名称
* @return 返回属性变量名称为PropertyName的属性值 
*/
public Object getPropertyValue(Object obj, String PropertyName) {
   ClassMetadata classMetadata = getHibernateTemplate()
     .getSessionFactory().getClassMetadata(obj.getClass());
   return classMetadata.getPropertyValue(obj, PropertyName,
     org.hibernate.EntityMode.POJO);
}
 
 
/**
* @Description: 返回包含<字段名,字段值>的MAP.只包含指标值.
* @param 映射的对象
* @return
*/
public Map getTargetMap(Obiect object) {
   Map targetMap = new LinkedHashMap();
   SessionFactory factory = getHibernateTemplate().getSessionFactory();
   AbstractEntityPersister classMetadata = (SingleTableEntityPersister) factory
     .getClassMetadata(Obiect.class);
   String[] propertyNames = classMetadata.getPropertyNames();
   for (String propertyName : propertyNames) {
    // --- 去掉集合类属性
    boolean isCollection = classMetadata.getClassMetadata()
      .getPropertyType(propertyName).isCollectionType();
    if (!isCollection) {
     String columnName = getColumnName(Obiect.class,
       propertyName);
     Object object1 = getPropertyValue(object1, propertyName);
     if (object1 != null && object1 instanceof Double) {
      // 依据如果是Double,代表是要处理的指标值.
      Double columnValue = (Double) object1;
      targetMap.put(columnName, columnValue);
     }
    }
   }
   return targetMap;
}
 
 
 

你可能感兴趣的:(SQL,Hibernate)