hibernate 整体介绍
在 myeclipse 中开发 hibernate 程序
1. myEclipse 中配置数据源
2. 创建 web 工程
3. 导入 hibernate 包
4. 按照向导配置
5. 根据表反向生成配置文件
6. 测试
public class UserTest {
private void save(){
User user = new User(111,"小明","123456");
Session session = HibernateSessionFactory.getSession();
//开启事务
Transaction tran = session.beginTransaction();
session.save(user);
tran.commit();
session.close();
}
private void update(){
User user = new User(111,"小明2","1111");
Session session = HibernateSessionFactory.getSession();
Transaction tran = session.beginTransaction();
session.update(user);
tran.commit();
session.close();
}
private void delete(){
//只需要有id值就可以
User user = new User(5);
Session session = HibernateSessionFactory.getSession();
Transaction tran = session.beginTransaction();
session.delete(user);
tran.commit();
session.close();
}
private void queryById(){
Session session = HibernateSessionFactory.getSession();
Transaction tran = session.beginTransaction();
User user = (User) session.get(User.class, 11);
System.out.println(user.getUid());
System.out.println(user.getName());
System.out.println(user.getPassword());
tran.commit();
session.close();
}
public static void main(String[] args) {
new UserTest().queryById();
}
}
可见,hibernate 简化了数据库操作。
HQL 语句:
from User;
使用 hql 查询 user 表全部数据:
private void getAll(){
String hql = "from User";
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(hql);
List<User> list = query.list();
for(User user : list){
System.out.println(user.getUid() +
"\t"+user.getName()+"\t"+user.getPassword());
}
}
使用 hql 查询 user 表全部用户名:
private void getAllNames(){
String hql = "select name from User";
// String hql = "select u.name from User as u";
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(hql);
List<String> list = query.list();
for(String name : list){
System.out.println(name);
}
}
使用 hql 查询全部用户名和密码:
private void getAllNamesPwd(){
String hql = "select password,name from User";
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(hql);
List<Object[]> list = query.list();
for(Object[] obj : list){
System.out.println(obj[0]+"\t"+obj[1]);
}
}
如果 select 后返回的属性都是某个持久类的属性,而没有聚合函数等,则可以使用类的构造
方法,返回持久类的对象,代码如下所示:
private void getAllNamesPwd2(){
String hql = "select new User(name,password) from User";
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(hql);
List<User> list = query.list();
for(User u : list){
System.out.println(u.getName()+"\t"+u.getPassword());
}
}
当然,要使用这种方式,前提是在 User 类中要有如 User(name,pssword)的构造方法。