package com.metis.hibernate.test; import java.util.Iterator; import java.util.List; import org.hibernate.Session; import com.metis.hibernate.domain.Person; import com.metis.hibernate.util.HibernateUtil; /** * 使用原生SQL的查询 * 你可以使用createSQLQuery()方法,用SQL来描述查询, * 并由Hibernate处理将结果集转换成对象的工作。 * 请注意,你可以在任何时候调用session.connection()来获得并使用JDBC Connection对象。 * 如果你选择使用Hibernate的API, 你必须把SQL别名用大括号包围起来 * * */ public class TestSqlQuery { public static void main(String[] args) { Session session = HibernateUtil.openSession(); List list = session.createSQLQuery("select {p.*} from person {p} where {p}.age > 20") .addEntity("p", Person.class) .list(); Iterator it = list.iterator(); while(it.hasNext()){ Person person = it.next(); System.out.print(" id:"+person.getId()); System.out.print(" name:"+person.getName()); System.out.println(" age:"+person.getAge()); } HibernateUtil.closeSession(); } }
Hibernate入门实例——使用原生SQL的查询
最新推荐文章于 2019-10-27 20:58:49 发布