1. 查询整个映射对象所有字段
String hql = "from Users" ;
Query query = session.createQuery(hql);
List<Users> users = query.list();
for (Users user : users){
System.out.println(user.getName() + " : " + user.getPasswd() + " : " + user.getId());
}
输出结果为:
name1 : password1 : 1
name2 : password2 : 2
name3 : password3 : 3
|
2.查询字段
String hql = " select name,passwd from Users" ;
Query query = session.createQuery(hql);
List<Object[]> list = query.list();
for (Object[] object : list){
String name = (String)object[ 0 ];
String passwd = (String)object[ 1 ];
System.out.println(name + " : " + passwd);
}
输出结果为:
name1 : password1
name2 : password2
name3 : password3
|
3.修改默认查询结果(query.list())不以Object[]数组形式返回,以List形式返回
String hql = " select new list(name,passwd) from Users" ;
Query query = session.createQuery(hql);
List<List> list = query.list();
for (List user : list){
String name = (String)user.get( 0 );
String passwd = (String)user.get( 1 );
System.out.println(name + " : " + passwd);
}
/**
输出结果为:
name1 : password1
name2 : password2
name3 : password3
*/
|
4.修改默认查询结果(query.list())不以Object[]数组形式返回,以Map形式返回
String hql = " select new map(name,passwd) from Users" ;
Query query = session.createQuery(hql);
List<Map> list = query.list();
for (Map user : list){
String name = (String)user.get( "0" );
String passwd = (String)user.get( "1" );
System.out.println(name + " : " + passwd);
}
/**
输出结果为:
name1 : password1
name2 : password2
name3 : password3
*/
|
5.修改默认查询结果(query.list())不以Object[]数组形式返回,以自定义类型返回
6.条件查询
String hql = "from Users where name=? and passwd=?" ;
Query query = session.createQuery(hql);
query.setParameter( 0 , "name1" ,Hibernate.STRING);
query.setParameter( 1 , "password1" ,Hibernate.STRING);
List<Users> list = query.list();
for (Users users : list){
System.out.println(users.getId());
}
|
String hql = "from Users where name=:username and passwd=:password" ;
Query query = session.createQuery(hql);
query.setParameter( "username" , "name1" ,Hibernate.STRING);
query.setParameter( "password" , "password1" ,Hibernate.STRING);
List<Users> list = query.list();
for (Users users : list){
System.out.println(users.getId());
}
|
String hql = "from Users where name=:username and passwd=:password" ;
Query query = session.createQuery(hql);
MyUser myUser = new MyUser( "name1" , "password1" );
query.setProperties(myUser);
List<Users> list = query.list();
for (Users users : list){
System.out.println(users.getId());
}
|
7.update 数据
执行SQL语句(为什么要用SQL语句,我想是为了执行某些复杂的SQL语句吧)
String sql= "update Table set field = 'test'"
Session session = HibernateSessionFactory.getSession();
session.createSQLQuery(sql).executeUpdate();
ts.commit();
|
执行HQL语句
String hql= "update Table set field = 'test'"
|
Session session = HiberanteSessionFactory.getSession();
Transaction ts = session.beginTransaction();
Query query = session.createQuery(hql);
query.executeUpdate();
ts.commit();
|