JPA查询--使用原生sql查询

 

1.如果sql 查询多个字段,   query.getResultList() 返回List类型每个对象类型是Obejct类型的数组。List<Object[]>

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public class JpaDemoTest {
	@PersistenceContext
	private EntityManager em;

	public void testJpaNativeQuery() {

		BigDecimal classNo = null;		
		BigDecimal studentNo = null;
		String remark = null;
	
		String sql = "select t.class_no ,t.student_no ,t.remark   from t_student t where t.class_no =:class_no ";
		Query query = em.createNativeQuery(sql);
		query.setParameter("class_no", 20);
		//返回Object[] 类型的List
		List objecArraytList = query.getResultList();
		for (int i = 0; i < objecArraytList.size(); i++) {
			//每个结果是Obect[] 类型
			Object[] obj = (Object[]) objecArraytList.get(i);
			classNo = (BigDecimal) obj[0];
			studentNo = (BigDecimal) obj[1];
			remark = (String) obj[2];
		}
		System.out.println("classNo==" + classNo + ";studentNo==" + studentNo + ";remark==" + remark);
	}

}

2.如果sql 查询一个字段,   query.getResultList() 返回List类型每个对象类型是Obejct。List<Object>

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public class JpaDemoTest {
	@PersistenceContext
	private EntityManager em;

	public void testJpaNativeQuery() {

		BigDecimal classNo = null;		
	
		String sql = "select t.class_no  from t_student t where t.class_no =:class_no ";
		Query query = em.createNativeQuery(sql);
		query.setParameter("class_no", 20);
		//返回Object 类型的List
		List objecArraytList = query.getResultList();
		for (int i = 0; i < objecArraytList.size(); i++) {
			//每个结果是Obect类型
			classNo = (BigDecimal) objecArraytList.get(i);
		}
		System.out.println("classNo==" + classNo );
	}

}

 

posted on 2019-07-18 16:52  dreamstar  阅读(1775)  评论(0编辑  收藏  举报