spring data jpa 想使用EntityManager 对sql 进行处理四种方式(第四种本人改写的)

下面看看主体的一个类:

package com.chinait.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.websocket.server.ServerEndpoint;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;

import com.chinait.service.TestService;
import com.chinait.utils.Testtrans;
import com.chinait.vo.Test;

@Service
public class TestServiceImpl implements TestService{
	@PersistenceContext
	private EntityManager entityManager;
	@Override	
	public void getTest(){
		String sql = "select apps.appName,source.cutPath,sourcetype.sourceTypeName from apps join source on source.apps_id = apps.id join sourcetype on sourcetype.id = source.sourceType_id";
		Session session = entityManager.unwrap(org.hibernate.Session.class);
		//返回类型是List<map>
		SQLQuery query2 = session.createSQLQuery(sql);
		query2.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		System.out.println("查询数据返回map"+query2.list());
		//返回数据是list<List<Object>>
		SQLQuery query3 = session.createSQLQuery(sql);
		query2.setResultTransformer(Transformers.TO_LIST);
		System.out.println("查询数据返回map"+query2.list());
		//返回类型是可定制化对象
		SQLQuery query = session.createSQLQuery(sql);
		Testtrans Testtrans = new Testtrans(Test.class);
		query.setResultTransformer(Testtrans);
		List<Test> list = (List<Test>)query.list();
		System.out.println("查询数据返回对象"+list);
		//返回数据是对象,首先这个方法有点坑,因为它需要去找寻bean 对应的对象是否是放在spring data jpa 的entity 如果不是的话回报错
		/*SQLQuery query4 = session.createSQLQuery(sql);
		query.setResultTransformer(Transformers.aliasToBean(Test.class));
		List<Test> list3 = (List<Test>)query.list();
		System.out.println("查询数据返回对象"+list);*/
	}
}
下面则是:我重写的一个类的源码:

package com.chinait.utils;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.transform.AliasToBeanResultTransformer;


public class Testtrans extends AliasToBeanResultTransformer{
	private Class resultClass;
	public Testtrans(Class resultClass) {
		super(resultClass);
		this.resultClass = resultClass;
	}

	private static final long serialVersionUID = 1L;

	public List transformTuple(Object[] tuple, String[] aliases) {
		  List list = new ArrayList();
		  Object obj = null;
			try {
				obj = resultClass.newInstance();
			} catch (InstantiationException e1) {
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			}
		  Method[] methods = resultClass.getMethods();// 返回这个类里面方法的集合  
		  for(int k=0;k<aliases.length;k++){
			  String aliase=aliases[k];
			  char[] ch = aliase.toCharArray();  
			  ch[0] = Character.toUpperCase(ch[0]);  
			  String s = new String(ch);  
			  String[] names = new String[] { ("set" + s).intern(),  
			    ("get" + s).intern(), ("is" + s).intern(),  
			    ("read" + s).intern() };  
			  Method setter = null;  
			  Method getter = null;  
			  int length = methods.length;  
			  for (int i = 0; i < length; ++i) {  
			   Method method = methods[i];  
			   /** 
			    * 检查该方法是否为公共方法,如果非公共方法就继续 
			    */  
			   if (!Modifier.isPublic(method.getModifiers()))  
			    continue;  
			   String methodName = method.getName();  
			  
			   for (String name : names) {  
			    if (name.equals(methodName)) {  
			     if (name.startsWith("set") || name.startsWith("read"))  
			      setter = method;  
			     else if (name.startsWith("get") || name.startsWith("is"))  
			      getter = method;  
			  
			    }  
			   }  
			  }
			  if(getter!=null){
				  Object[] param = buildParam(getter.getReturnType().getName(), tuple[k]);  
				  try {  
				   setter.invoke(obj, param);
				  } catch (Exception e) {  
				   e.printStackTrace();  
				  }
			  }
		  }
		  list.add(obj);
		  return list;
	}
	private final static Object[] buildParam(String paramType, Object value) {  
		  Object[] param = new Object[1];  
		  if (paramType.equalsIgnoreCase("java.lang.String")) {  
		   param[0] = (String)(value);  
		  } else if (paramType.equalsIgnoreCase("int")  
		    || paramType.equalsIgnoreCase("java.lang.Integer")) {  
		   param[0] = (Integer)(value);  
		  } else if (paramType.equalsIgnoreCase("long")|| paramType.equalsIgnoreCase("java.lang.Long")) {  
		   param[0] = (Long)(value);  
		  } else if (paramType.equalsIgnoreCase("double")|| paramType.equalsIgnoreCase("java.lang.Double")) {  
		   param[0] = (Double)(value);  
		  } else if (paramType.equalsIgnoreCase("float")|| paramType.equalsIgnoreCase("java.lang.Float")) {  
		   param[0] = (Float)(value);  
		  } else if (paramType.equalsIgnoreCase("char")  
		    || paramType.equalsIgnoreCase("Character")) {  
		   param[0] = (char)(value);  
		  }  
		  return param;  
	}  
}
注意Test 的实体类:

package com.chinait.vo;
//apps.appName,source.cutPath,sourcetype.sourceTypeName
public class Test {
	private String appName;
	private String cutPath;
	private String sourceTypeName;
	public String getAppName() {
		return appName;
	}
	public void setAppName(String appName) {
		this.appName = appName;
	}
	public String getCutPath() {
		return cutPath;
	}
	public void setCutPath(String cutPath) {
		this.cutPath = cutPath;
	}
	public String getSourceTypeName() {
		return sourceTypeName;
	}
	public void setSourceTypeName(String sourceTypeName) {
		this.sourceTypeName = sourceTypeName;
	}
	@Override
	public String toString() {
		return "Test [appName=" + appName + ", cutPath=" + cutPath + ", sourceTypeName=" + sourceTypeName + "]";
	}
}

输出结果:


*注意这里还有一个bug,那就是select * 这里会报错,因为sqlquery 是按照字段的别名来判断数据与实体的对应关系。所以这里如果写成是select * 回报一个异常是指无法匹配

这边有兴趣的就是看这个源码。spring data jpa 想使用entityManager 对sql 进行处理四种方式(第四种本人改写的)。

猜你喜欢

转载自blog.csdn.net/sai739295732/article/details/68490812
今日推荐