怎样使用泛型实现Hibernate查询返回对象

 我来答
胖嘟嘟的蜗牛
2017-01-16
知道答主
回答量:16
采纳率:0%
帮助的人:5.3万
展开全部

我可以给你demo,你可以参考

接口你可以自己写

package com.shopping.b2b.dao.impl;


import java.io.Serializable;

import java.lang.reflect.Field;

import java.util.Collection;

import java.util.List;

import java.util.Map;


import javax.annotation.Resource;

import javax.persistence.Table;


import org.apache.log4j.Logger;

import org.hibernate.Hibernate;

import org.hibernate.Query;

import org.hibernate.SQLQuery;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.transform.Transformers;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;


import com.shopping.b2b.dao.ISuperDao;


@Repository("superDao")

public class SuperDaoImpl implements ISuperDao{

@Resource

private SessionFactory hibernateSessionFactory;

public SessionFactory getHibernateSessionFactory() {

return hibernateSessionFactory;

}


public void setHibernateSessionFactory(SessionFactory hibernateSessionFactory) {

this.hibernateSessionFactory = hibernateSessionFactory;

}

private Logger logger = Logger.getLogger(this.getClass());

private Session getCurrentSession() {

return this.hibernateSessionFactory.getCurrentSession();

}


@Override

public <T> T get(Class<T> clazz, Serializable id) {

return (T)this.getCurrentSession().get(clazz, id);

}

@Override

public <T> T getSql(String sql, Map<String, Object> params, Class<T> po) {

SQLQuery q = this.getCurrentSession().createSQLQuery(sql);

/*

* say:

* 从数据库查出来的数据类型给po,如果要自定义,那么需要扩展addScalar

* 默认情况:数据库字段类型是什么类型,返回的po也是什么类型。移植性不好

* 可扩展

*/

if(po != null){

q.setResultTransformer(Transformers.aliasToBean(po));

}else{

q.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

}

if(params != null && !params.isEmpty()){

for (String k : params.keySet()) {

Object v = params.get(k);

if(v != null){

if(v instanceof Object[]){

q.setParameterList(k, (Object[])v);

}else if(v instanceof Collection<?>){

q.setParameterList(k, (Collection<?>)v);

}else{

q.setParameter(k, v);

};

}

}

}

List<T>  list = q.list();

return list == null || list.isEmpty() ? null:list.get(0);

}

@Override

public Serializable save(Object entity) {

return this.getCurrentSession().save(entity);

}


@Override

public boolean update(Object entity) {

boolean result = false;

try {

this.getCurrentSession().update(entity);

result = true;

} catch (Exception e) {

result = false;

}

return result;

}

@Override

public boolean updateSql(String sql,Map<String, Object> params) {

SQLQuery q = this.getCurrentSession().createSQLQuery(sql);

if(params != null && !params.isEmpty()){

for (String k : params.keySet()) {

Object v = params.get(k);

if(v != null){

if(v instanceof Object[]){

q.setParameterList(k, (Object[])v);

}else if(v instanceof Collection<?>){

q.setParameterList(k, (Collection<?>)v);

}else{

q.setParameter(k, v);

};

}

}

}

return q.executeUpdate() == 0 ? false :true;

}


@Override

public boolean delete(Object entity) {

boolean result = false;

try {

this.getCurrentSession().delete(entity);

result = true;

} catch (Exception e) {

result = false;

}

return result;

}

@Override

public <T> boolean deleteSql(Class<T> clazz,Serializable id) {

boolean result = false;

try {

Table table = (Table)clazz.getAnnotation(Table.class);

if(table != null){

String tableName = table.name();

this.getCurrentSession()

.createSQLQuery("delete from :tableName where id = :id")

.setParameter("tableName", tableName)

.setParameter("id", id)

.executeUpdate();

}

result = true;

} catch (Exception e) {

result = false;

}

return result;

}

@Override

public <T> List<T> queryList(String sql, Map<String, Object> params, Class<T> po) {

SQLQuery q = this.getCurrentSession().createSQLQuery(sql);

/*

* say:

* 从数据库查出来的数据类型给po,如果要自定义,那么需要扩展addScalar

* 默认情况:数据库字段类型是什么类型,返回的po也是什么类型。移植性不好

* 可扩展

*/

if(po != null){

q.setResultTransformer(Transformers.aliasToBean(po));

}else{

q.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

}

if(params != null && !params.isEmpty()){

for (String k : params.keySet()) {

Object v = params.get(k);

if(v != null){

if(v instanceof Object[]){

q.setParameterList(k, (Object[])v);

}else if(v instanceof Collection<?>){

q.setParameterList(k, (Collection<?>)v);

}else{

q.setParameter(k, v);

}

}

}

}

List<T>  list = q.list();

return list == null || list.isEmpty() ? null:list;

}

@Override

public <T> List<T> queryList(String sql, Map<String, Object> params, int firstResult, int maxResults, Class<T> po) {

SQLQuery query = this.getCurrentSession().createSQLQuery(sql);

/*

* say:

* 从数据库查出来的数据类型给po,如果要自定义数据类型,那么需要扩展addScalar

* 默认情况:数据库字段类型是什么类型,返回的po也是什么类型。移植性不好

* 可扩展

*/

if(po != null){

query.setResultTransformer(Transformers.aliasToBean(po)).setFirstResult(firstResult).setMaxResults(maxResults);

}else{

query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setFirstResult(firstResult).setMaxResults(maxResults);

}

//this.addScalarsToString(query, po).setFirstResult(firstResult).setMaxResults(maxResults);//test

if(params != null && !params.isEmpty()){

for (String k : params.keySet()) {

Object v = params.get(k);

if(v != null){

if(v instanceof Object[]){

query.setParameterList(k, (Object[])v);

}else if(v instanceof Collection<?>){

query.setParameterList(k, (Collection<?>)v);

}else{

query.setParameter(k, v);

}

}

}

}

List<T>  list = query.list();

return list == null || list.isEmpty() ? null:list;

}


@Override

public <T> Serializable queryCount(String sql, Map<String, Object> params) {

Query query = this.getCurrentSession().createSQLQuery(sql);

if(params != null && !params.isEmpty()){

for (String k : params.keySet()) {

Object v = params.get(k);

if(v != null){

if(v instanceof Object[]){

query.setParameterList(k, (Object[])v);

}else if(v instanceof Collection<?>){

query.setParameterList(k, (Collection<?>)v);

}else{

query.setParameter(k, v);

}

}

}

}

return Integer.parseInt(query.uniqueResult().toString());

}

/**

* 扩展

* 默认将class的属性类型转换为hibernate所对应的的类型<br/>

* 如果严格的话请使用Transformers.aliasToBean(T.class)<br/>

* 对应表如下:

* 未实现

* @param query

* @param cls

* @return

*/

private  <T> Query addScalarsToCustom(SQLQuery query,Class<T> cls){

Field[] fields = cls.getDeclaredFields();

for(Field item:fields){

////System.out.println(item.getName() + ":" + item.getGenericType());

//该接口需要判断,返回的属性类型,然后转换为hibernate语法

//System.out.println(item.getName() + ":" + item.getGenericType());

//该接口需要判断,返回的属性类型,然后转换为hibernate语法

if("class java.math.BigInteger".equals(item.getGenericType().toString())){

//System.out.println(cls.getName() +":"+item.getName()  + "    ||==int");

}else if("class java.lang.String".equals(item.getGenericType().toString())){

//System.out.println(cls.getName() +":"+item.getName()  +  "    ||==String");

}else if("class java.math.BigDecimal".equals(item.getGenericType().toString())){

//System.out.println(cls.getName() +":"+item.getName()  +  "    ||==String");

}else{

//System.out.println(cls.getName() +":"+item.getName()  +  "    ||==未匹配类型");

}

}

return null;

}




}

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式