hibernate 中的 HQL 语句查询,类似于 SQL;
public class SearchTest {
public static void main(String[] args){
Session session = null;
Transaction transaction = null;
try{
session = HibUtil.getSession();
transaction = session.beginTransaction();
String hql = "from Studentinfo";
Query q = session.createQuery(hql);
List<Studentinfo> list = q.list();
for(int i=0; i<list.size();i++){
Studentinfo stu = list.get(i);
System.out.println("Name: "+stu.getUsername());
System.out.println("Phone:"+stu.getUserphone());
}
transaction.commit();
}catch (Exception e) {
e.printStackTrace();
}
finally{
if(session != null ){
session.close();
}
}
}
}
其他查询方式:
//单个对象
String hql = "select count(*) from Studentinfo";
Query q = session.createQuery(hql);
Number n = (Number) q.uniqueResult();
//Object[]数组 值得到需要的属性
String hql = "select s.name,s.phone from Studentinfo s";
List<Object[]> list = q.list();
for(int i=0; i < list.size(); i++){
Object[] os = list.get(i);
}
//实体对象
String hql = "select new Studentinfo(s.name,s.phone) from Student s";
//......
//where子句参数传递
//String hql = "from Studentinfo where name = ?";
String hql = "from Studentinfo where name=:name";//参数名称动态绑定
Query q = session.createQuery(hql);
//q.setString(0,"smith");
q.setString("name", "smith");
//SQL查询
String sql = "select * from studentinfo where name=:name";
SQLQuery q = session.createSQLQuery(sql);
//......
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于