hibernate对数据库的查询其实有很多种方法,下面我来介绍我知道的两种方法,以及它们可能会遇到的问题,这里前两种都是查询所有结果
最后一种是 使用hibernate查询一条记录。
第一种方法
public void queryTest() { Configuration configuration = new Configuration();//默认就是加载hibernate.cfg.xml configuration.configure(); //获得会话工厂,创建会话 SessionFactory buildSessionFactory = configuration.buildSessionFactory(); //获得session Session session = buildSessionFactory.openSession(); //开启事务 Transaction tx = session.beginTransaction();
//注意这个地方,直接from 就行,from后面跟的是自己建的bean类名,不是表名 Query createQuery = session.createQuery("from Student");
List<Student> students = createQuery.list(); for(Student student:students) { System.out.println(student); } //关闭资源 session.close(); buildSessionFactory.close(); }
!!!!!!! 这种查询方式大家注意了,这里我的bean名字是Student,所以上面是from Student
第二种方法:
package com.cidp.test; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import com.cidp.pojo.Student; public class MyTest { //测试插入数据 @Test public void queryTest() { Configuration configuration = new Configuration();//默认就是加载hibernate.cfg.xml configuration.configure(); //获得会话工厂,创建会话 SessionFactory buildSessionFactory = configuration.buildSessionFactory(); //获得session Session session = buildSessionFactory.openSession(); //开启事务 Transaction tx = session.beginTransaction();
//这种主要就是自己写sql语句,这里就是sql怎么写就是怎样的了。 Query query = session.createSQLQuery("select * from stu_info").addEntity(Student.class); List<Student> list = (List<Student>)query.list(); for(Student student:list) { System.out.println(student); } //关闭资源 session.close(); buildSessionFactory.close(); } }
第三种:
package com.cidp.test; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import com.cidp.pojo.Student; public class MyTest { //测试插入数据 @Test public void queryOneTest() { Configuration configuration = new Configuration();//默认就是加载hibernate.cfg.xml configuration.configure(); //获得会话工厂,创建会话 SessionFactory buildSessionFactory = configuration.buildSessionFactory(); //获得session Session session = buildSessionFactory.openSession(); //开启事务 Transaction tx = session.beginTransaction(); Query query = session.createSQLQuery("select * from stu_info where id = 2");
//返回的是Object[], 存放的是一条数据中,的每一列元素,例如2 李四 123456 Object[] uniqueResult = (Object[]) query.uniqueResult(); for(Object object : uniqueResult) { System.out.print(object + " "); } System.out.println(); //关闭资源 session.close(); buildSessionFactory.close(); } }