使用HIBERNATE的SQL查询并将结果集自动转换成POJO
2010-03-16 20:36
405 查看
使用HIBERNATE的SQL查询并将结果集自动转换成POJO
文章分类:Java编程在某些场合下,我们可能想使用HIBERNATE的框架提供的SQL查询接口,这时,由于表和实体都可能没有做映射,HIBERNATE不能把结果集转换
成你想要的List<POJO>,本文讨论如何在这种情况下让HIBERNATE直接返回你想的结果。下面是简单的查询封装方法
Java代码
public
List<? extends
BaseModel> findObjectBySql(String queryString,Class<? extends
BaseModel> pojoClass){
//使用SQL构造查询对象,此SQL是可以被JDBC接受的SQL,如SELECT * FROM XXX_TABLE
Query query = this
.getSession().createSQLQuery(queryString);
//设置结果集转换器,这是本文重点所在
query.setResultTransformer(new
EscColumnToBean(pojoClass));
//返回查询结果
return
query.list();
public List<? extends BaseModel> findObjectBySql(String queryString,Class<? extends BaseModel> pojoClass){ //使用SQL构造查询对象,此SQL是可以被JDBC接受的SQL,如SELECT * FROM XXX_TABLE Query query = this.getSession().createSQLQuery(queryString); //设置结果集转换器,这是本文重点所在 query.setResultTransformer(new EscColumnToBean(pojoClass)); //返回查询结果 return query.list();
上面这个方法很简单,如果查的是USER表,并且pojoClass参数传入的就是USER.class的话,那么返回结果集的就是
List<User>。当然在我的应用中还有查询条件封装,分页和自动查询总行数等逻辑,不想把主题分散,所以给省略了。
下面是结果集转换器的完整代码
Java代码
package
com.lgdlgd.hibernate;
import
java.lang.reflect.Field;
import
java.util.List;
import
org.hibernate.HibernateException;
import
org.hibernate.property.ChainedPropertyAccessor;
import
org.hibernate.property.PropertyAccessor;
import
org.hibernate.property.PropertyAccessorFactory;
import
org.hibernate.property.Setter;
import
org.hibernate.transform.ResultTransformer;
import
com.esc.common.baseclass.BaseModel;
/**
* 自定义的数据库字库转换成POJO
*/
public
class
EscColumnToBean implements
ResultTransformer {
private
static
final
long
serialVersionUID = 1L;
private
final
Class<? extends
BaseModel> resultClass;
private
Setter[] setters;
private
PropertyAccessor propertyAccessor;
public
EscColumnToBean(Class<? extends
BaseModel> resultClass) {
if
(resultClass==null
) throw
new
IllegalArgumentException("resultClass cannot be null"
);
this
.resultClass = resultClass;
propertyAccessor = new
ChainedPropertyAccessor(new
PropertyAccessor[] { PropertyAccessorFactory.getPropertyAccessor(resultClass,null
), PropertyAccessorFactory.getPropertyAccessor("field"
)});
}
//结果转换时,HIBERNATE调用此方法
public
Object transformTuple(Object[] tuple, String[] aliases) {
Object result;
try
{
if
(setters==null
) {//首先初始化,取得目标POJO类的所有SETTER方法
setters = new
Setter[aliases.length];
for
(int
i = 0
; i < aliases.length; i++) {
String alias = aliases[i];
if
(alias != null
) {
//我的逻辑主要是在getSetterByColumnName方法里面,其它都是HIBERNATE的另一个类中COPY的
//这里填充所需要的SETTER方法
setters[i] = getSetterByColumnName(alias);
}
}
}
result = resultClass.newInstance();
//这里使用SETTER方法填充POJO对象
for
(int
i = 0
; i < aliases.length; i++) {
if
(setters[i]!=null
) {
setters[i].set(result, tuple[i], null
);
}
}
} catch
(InstantiationException e) {
throw
new
HibernateException("Could not instantiate resultclass: "
+ resultClass.getName());
} catch
(IllegalAccessException e) {
throw
new
HibernateException("Could not instantiate resultclass: "
+ resultClass.getName());
}
return
result;
}
//根据数据库字段名在POJO查找JAVA属性名,参数就是数据库字段名,如:USER_ID
private
Setter getSetterByColumnName(String alias) {
//取得POJO所有属性名
Field[] fields = resultClass.getDeclaredFields();
if
(fields==null
|| fields.length==0
){
throw
new
RuntimeException("实体"
+resultClass.getName()+"不含任何属性"
);
}
//把字段名中所有的下杠去除
String proName = alias.replaceAll("_"
, ""
).toLowerCase();
for
(Field field : fields) {
if
(field.getName().toLowerCase().equals(proName)){//去除下杠的字段名如果和属性名对得上,就取这个SETTER方法
return
propertyAccessor.getSetter(resultClass, field.getName());
}
}
throw
new
RuntimeException("找不到数据库字段 :"
+ alias + " 对应的POJO属性或其getter方法,比如数据库字段为USER_ID或USERID,那么JAVA属性应为userId"
);
}
@SuppressWarnings
("unchecked"
)
public
List transformList(List collection) {
return
collection;
}
}
package com.lgdlgd.hibernate; import java.lang.reflect.Field; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.property.ChainedPropertyAccessor; import org.hibernate.property.PropertyAccessor; import org.hibernate.property.PropertyAccessorFactory; import org.hibernate.property.Setter; import org.hibernate.transform.ResultTransformer; import com.esc.common.baseclass.BaseModel; /** * 自定义的数据库字库转换成POJO */ public class EscColumnToBean implements ResultTransformer { private static final long serialVersionUID = 1L; private final Class<? extends BaseModel> resultClass; private Setter[] setters; private PropertyAccessor propertyAccessor; public EscColumnToBean(Class<? extends BaseModel> resultClass) { if(resultClass==null) throw new IllegalArgumentException("resultClass cannot be null"); this.resultClass = resultClass; propertyAccessor = new ChainedPropertyAccessor(new PropertyAccessor[] { PropertyAccessorFactory.getPropertyAccessor(resultClass,null), PropertyAccessorFactory.getPropertyAccessor("field")}); } //结果转换时,HIBERNATE调用此方法 public Object transformTuple(Object[] tuple, String[] aliases) { Object result; try { if(setters==null) {//首先初始化,取得目标POJO类的所有SETTER方法 setters = new Setter[aliases.length]; for (int i = 0; i < aliases.length; i++) { String alias = aliases[i]; if(alias != null) { //我的逻辑主要是在getSetterByColumnName方法里面,其它都是HIBERNATE的另一个类中COPY的 //这里填充所需要的SETTER方法 setters[i] = getSetterByColumnName(alias); } } } result = resultClass.newInstance(); //这里使用SETTER方法填充POJO对象 for (int i = 0; i < aliases.length; i++) { if(setters[i]!=null) { setters[i].set(result, tuple[i], null); } } } catch (InstantiationException e) { throw new HibernateException("Could not instantiate resultclass: " + resultClass.getName()); } catch (IllegalAccessException e) { throw new HibernateException("Could not instantiate resultclass: " + resultClass.getName()); } return result; } //根据数据库字段名在POJO查找JAVA属性名,参数就是数据库字段名,如:USER_ID private Setter getSetterByColumnName(String alias) { //取得POJO所有属性名 Field[] fields = resultClass.getDeclaredFields(); if(fields==null || fields.length==0){ throw new RuntimeException("实体"+resultClass.getName()+"不含任何属性"); } //把字段名中所有的下杠去除 String proName = alias.replaceAll("_", "").toLowerCase(); for (Field field : fields) { if(field.getName().toLowerCase().equals(proName)){//去除下杠的字段名如果和属性名对得上,就取这个SETTER方法 return propertyAccessor.getSetter(resultClass, field.getName()); } } throw new RuntimeException("找不到数据库字段 :"+ alias + " 对应的POJO属性或其getter方法,比如数据库字段为USER_ID或USERID,那么JAVA属性应为userId"); } @SuppressWarnings("unchecked") public List transformList(List collection) { return collection; } }
我这个转换器工作的前提是数据库的字段名除了可以含有下杠外,不能再含有其它 POJO对应属性中没有的字符,如USER_ID 对应POJO的userId。
扩展点:
1、可以自定义数据库与POJO属性的对应关系,在查询方法中构造转换器时,通过参数把转换关系传入进来,这样就可实现自由转换了,但请注意这种
转换关系只有非常通用才有价值(上面的转换规则就是:字段名 去除下杠 =
JAVA属性名),反之如果每个实体都有自已的转换关系,那就还不如编写一个HIBERNATE的映射文件了。
2、本类没有考虑关联,即自定义的对象属性,但这些都不难实现,有兴趣的朋友可结合我的第一篇文章来实现
注意:HIBERNATE3.25以前(后面的没看),对SQL查询的CHAR类型字段处理不好,只返回一位,且是JAVA的CHAR类型,要修改CharacterType类的代码以返回该类型字段的全值
后记:刚才有朋友说到,HIBERNATE本身也支持这种封装,直接使用HIBERNATE原有的封装:
Java代码
Query query = this
.getSession().createSQLQuery(queryString).addEntity(pojoClass);
Query query = this.getSession().createSQLQuery(queryString).addEntity(pojoClass);
这样后面就不需要设置结果转换器了,但是这样做的前提是实体必须要有映射
原创
:这里我要提示一点,有些时候,有些内容还是不能转换,因为数据类型不一样。这时候就要自己去修改了,将
Object[] tuple,tuple[i]中的变量类型修改,比如tuple[0]中有个变量a 是Long型,但是tuple[i]中的是Bigcimal,
这时候,就要自己写个类比如 chgObject(Object tuple){ a =((BigCimal) tuple[i].getA()).longValue();}
相关文章推荐
- 使用HIBERNATE的SQL查询并将结果集自动转换成POJO
- 使用HIBERNATE的SQL查询并将结果集自动转换成POJO
- 使用HIBERNATE的SQL查询并将结果集自动转换成POJO
- 使用HIBERNATE的SQL查询并将结果集自动转换成POJO
- Hibernate3.2.6 原生sql 查询使用方法,将查询结果直接转换为POJO,不必非要指定属性大写
- hibernate中使用sql语句进行表链接查询,对结果集的遍历方法
- hibernate使用原生SQL查询返回结果集的处理
- hibernate在使用sql查询query自动转化成model类型数据,query.addEntity
- 关于hibernate使用SQL查询,结果集无法映射到实体类上
- Hibernate自定义SQL查询结果自动反射到POJO
- hibernate使用原生SQL查询返回结果集的处理
- hibernate使用原生的sql,解决管理查询、结果集封装等问题
- hibernate使用本地sql语句查询,解决List<Object[]>转换成List<实体>
- Jeecg中使用<t: dgCol>标签的自动构造查询条件时出现类型转换错误的解决办法。
- Hibernate使用sql进行查询的问题
- Hibernate使用sql进行查询的问题
- 使用addScala将SQLQuery自定义查询映射到pojo中
- Hibernate使用sql查询出map类型数据
- 任意一条查询sql转换为查询结果集对应的数目
- sql hibernate查询转换成实体或对应的VO Transformers