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);
				}
			}
		}
	}

 

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