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<String> resultList = new ArrayList<String>(); 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<String, Double> getTargetMap(Obiect object) { Map<String, Double> targetMap = new LinkedHashMap<String, Double>(); 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; }
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25