hibernate中的HQL语句查询,类似于SQL;
1 public class SearchTest { 2 public static void main(String[] args){ 3 Session session = null; 4 Transaction transaction = null; 5 try{ 6 session = HibUtil.getSession(); 7 transaction = session.beginTransaction(); 8 String hql = "from Studentinfo"; 9 Query q = session.createQuery(hql); 10 List<Studentinfo> list = q.list(); 11 for(int i=0; i<list.size();i++){ 12 Studentinfo stu = list.get(i); 13 System.out.println("Name: "+stu.getUsername()); 14 System.out.println("Phone:"+stu.getUserphone()); 15 } 16 transaction.commit(); 17 }catch (Exception e) { 18 e.printStackTrace(); 19 } 20 21 finally{ 22 if(session != null ){ 23 session.close(); 24 } 25 } 26 } 27 }
其他查询方式:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 //单个对象 2 String hql = "select count(*) from Studentinfo"; 3 Query q = session.createQuery(hql); 4 Number n = (Number) q.uniqueResult(); 5 6 //Object[]数组 值得到需要的属性 7 String hql = "select s.name,s.phone from Studentinfo s"; 8 List<Object[]> list = q.list(); 9 for(int i=0; i < list.size(); i++){ 10 Object[] os = list.get(i); 11 } 12 13 //实体对象 14 String hql = "select new Studentinfo(s.name,s.phone) from Student s"; 15 //...... 16 17 //where子句参数传递 18 //String hql = "from Studentinfo where name = ?"; 19 String hql = "from Studentinfo where name=:name";//参数名称动态绑定 20 Query q = session.createQuery(hql); 21 //q.setString(0,"smith"); 22 q.setString("name", "smith"); 23 24 //SQL查询 25 String sql = "select * from studentinfo where name=:name"; 26 SQLQuery q = session.createSQLQuery(sql); 27 //...... 28