原因:在使用Hibernate原生SQL查詢的時候,無法將字段名與屬性名正確對應(實際是對應的Bean的字段名映射關係)。
解決:
1.首先從獲取的PropertyDescriptor中獲取Get方法上的Column註解
2.獲取Column中的name屬性值
3.建立對應關係
protected void initialize(Class<?> mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap<String, PropertyDescriptor>();
this.mappedProperties = new HashSet<String>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
String aliasName = null;
for (PropertyDescriptor pd : pds) {
aliasName = null;
if(pd.getReadMethod() != null) {
Column columnAnnotation = pd.getReadMethod().getDeclaredAnnotation(Column.class);
if(columnAnnotation != null) {
aliasName = columnAnnotation.name();
}
}
if (pd.getWriteMethod() != null) {
if(StringUtils.isEmpty(aliasName)) {
String underscoredName = underscoreName(pd.getName());
if (!pd.getName().toLowerCase().equals(underscoredName)) {
this.mappedFields.put(underscoredName, pd);
}
this.mappedProperties.add(pd.getName());
}else{
this.mappedFields.put(aliasName.toLowerCase(), pd);
this.mappedProperties.add(aliasName);
}
}
}
}