this.getJpaTemplate() createNativeQuery

1. 下面那个类的返回类型要注意它返回的结果是List<Vector> 。
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class RatingRepositoryImpl extends JpaDaoSupport implements IRatingRepository {
	
	private double d;
	private EntityManager em;
	private Query query;	
		
	public double getAvgRating(Short type,long obj2){
		String sql = "select sum(r.degree)/count(*) from related r where r.type=?1 and r.obj2=?2";
		em = this.getJpaTemplate().getEntityManagerFactory().createEntityManager();
		query = em.createNativeQuery(sql);
		query.setParameter(1, type);
		query.setParameter(2, obj2);
		List<Vector> vlist = query.getResultList();
		if(vlist.size() > 0){
			Vector obj = vlist.get(0);
			d = Double.parseDouble((String)obj.get(0).toString());
		}
		return d;
	}

}

 2.还有下面是专门为了createNativeQuery()而做的解析返回结果的例子代码,以后可以借鉴。

public List<Movie> getMoviesFromVector(List<Vector> vList) {
		List<Movie> movies = new ArrayList<Movie>();
		for (Vector v : vList) {
			Movie movie = new Movie();
			Object aId = v.get(0);
			Object aTitle = v.get(1);
			Object aCover = v.get(2);
			Object aLength = v.get(3);
			Object aCreated = v.get(4);
			movie.setId(aId != null ? Long.parseLong((String) aId.toString())
					: 0);
			movie.setTitle(aTitle != null ? aTitle.toString() : "");
			movie.setCover(aCover != null ? aCover.toString() : "");
			movie.setLength(aLength != null ? Long.parseLong((String) aLength
					.toString()) : 0);
			movie.setCreated(aCreated != null ? (Timestamp)aCreated : null);
			movies.add(movie);
		}
		return movies;
}

 

你可能感兴趣的:(sql)