Hibernate原生SQL使用別名(表字段使用了別名與Bean中字段名不一致)後無法獲取數據的問題

原因:在使用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);
				}
			}
		}
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章