一、基本数据查询 使用Hibernate进行数据查询是一件简单的事,Java程序设计人员可以使用对象操作的方式来进行数据查询,查询时使用一种类似SQL的HQL(Hibernate Query Language)来设定查询的条件,与SQL不同的是,HQL是具备对象导向的继承、多型等特性的语言。 直接使用范例来看看如何使用Hibernate进行数据库查询,在这之前,请先照之前介绍过的主题在数据库中新增几笔数据: 在Hibernate中新增资料 查询数据时,我们所使用的是Session的find()方法,并在当中指定HQL设定查询条件,查询的结果会装载在List对象中传回,您所需要的是将它们一一取出,一个最简单的例子如下: HibernateTest.java
import onlyfun.caterpillar.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import java.util.*; public class HibernateTest {
public static void main(String[] args) throws HibernateException {
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession();
List users = session.find("from User");
session.close();
sessionFactory.close();
for (ListIterator iterator = users.listIterator(); iterator.hasNext(); ) {
User user = (User) iterator.next();
System.out.println(user.getName() +
"\n\tAge: " + user.getAge() +
"\n\tSex: " + user.getSex());
}
}
} | find()中的“from User”即HQL,User指的是User类别,藉由映射文件,它将会查询USER表格中的数据,相当于SQL中的SELECT * FROM USER,实际上我们的User类别是位于onlyfun.caterpillar下,Hibernate会自动看看import中的package名称与类别名称是否符合,您也可以直接指定package名称,例如:
session.find("from onlyfun.caterpillar.User"); | 这个程序的运行结果可能是这样的:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, user0_.age as age from USER user0_
caterpillar
Age: 28
Sex: M
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F | 上面所介绍的查询是最简单的,只是从数据表中查询所有的数据,Hibernate所查询得回的数据,是以对象的方式传回,以符合程序中操作的需要,我们也可以限定一些查询条件,并只传回我们指定的字段,例如:
List names = session.find("select user.name from User as user where age = 25");
for (ListIterator iterator = names.listIterator(); iterator.hasNext(); ) {
String name = (String) iterator.next();
System.out.println("name: " + name);
} | 在find()中的HQL示范了条件限定的查询,User as user为User类别取了别名,所以我们就可以使用user.name来指定表格传回字段,where相当于SQL中的WHERE子句,我们限定查询age等于25的数据,这次查询的数据只有一个字段,而型态是String,所以传回的List内容都是String对象,一个运行的例子如下:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select user0_.name as x0_0_ from USER user0_ where (age=25 )
name: momor
name: Bush | 如果要传回两个以上的字段,也不是什么问题,直接来看个例子:
List results = session.find("select user.name, user.age from User as user where sex = 'F'");
for (ListIterator iterator = results.listIterator(); iterator.hasNext(); ) {
Object[] rows = (Object[]) iterator.next();
String name = (String) rows[0];
Integer age = (Integer) rows[1];
System.out.println("name: " + name + "\n\t" + age);
} | 从上面的程序中不难看出,传回两个以上字段时,每一次ListIterator会以Object数组的方式传回一笔数据,我们只要指定数组索引,并转换为适当的型态,即可取得数据,一个查询的结果如下:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select user0_.name as x0_0_, user0_.age as x1_0_ from USER user0_ where (sex='F')
name: momor
25
name: Becky
35 | 您也可以在HQL中使用一些函数来进行结果统计,例如:
List results = session.find("select count(*), avg(user.age) from User as user");
ListIterator iterator = results.listIterator();
Object[] rows = (Object[]) iterator.next();
System.out.println("资料笔数: " + rows[0] + "\n平均年龄: " + rows[1]); | 一个查询的结果如下所示:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select count(*) as x0_0_, avg(user0_.age) as x1_0_ from USER user0_
资料笔数: 4
平均年龄: 28.25 | #p# 二、更新和删除数据 如果您是在同一个Session中取出数据并想要马上进行更新,则只要先查询并取出对象,透过setXXX()方法设定好新的值,然后呼叫session.flush()即可在同一个Session中更新指定的数据,例如: HibernateTest.java
import onlyfun.caterpillar.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import java.util.*; public class HibernateTest {
public static void main(String[] args) throws HibernateException {
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
List users = session.find("from User");
User updated = null;
for (ListIterator iterator = users.listIterator(); iterator.hasNext(); ) {
User user = (User) iterator.next();
if(updated == null)
updated = user;
System.out.println(user.getName() +
"\n\tAge: " + user.getAge() +
"\n\tSex: " + user.getSex());
}
updated.setName("justin");
session.flush();
users = session.find("from User");
session.close();
sessionFactory.close();
for (ListIterator iterator = users.listIterator(); iterator.hasNext(); ) {
User user = (User) iterator.next();
System.out.println(user.getName() +
"\n\tAge: " + user.getAge() +
"\n\tSex: " + user.getSex());
}
}
} | 这个程序会显示数据表中的所有数据,并将数据表中的第一笔数据更新,一个执行的结果如下:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, user0_.age as age from USER user0_
caterpillar
Age: 28
Sex: M
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F
Hibernate: update USER set name=?, sex=?, age=? where user_id=?
Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, user0_.age as age from USER user0_
justin
Age: 28
Sex: M
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F | 如果您开启了一个Session,从数据表中取出数据显示到使用者接口上,之后关闭Session,当使用者在接口上操作完毕并按下储存时,这时您要重新开启一个Session,使用update()方法将对象中的数据更新至对应的数据表中,一个例子如下: HibernateTest.java
import onlyfun.caterpillar.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import java.util.*;
public class HibernateTest {
public static void main(String[] args) throws HibernateException {
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
List users = session.find("from User");
// 关闭这个Session
session.close();
User updated = null;
for (ListIterator iterator = users.listIterator(); iterator.hasNext(); ) {
User user = (User) iterator.next();
if(updated == null)
updated = user;
System.out.println(user.getName() +
"\n\tAge: " + user.getAge() +
"\n\tSex: " + user.getSex());
}
// 使用者作一些操作,之后储存
updated.setName("caterpillar");
// 开启一个新的Session
session = sessionFactory.openSession();
// 更新数据
session.update(updated);
users = session.find("from User");
session.close();
sessionFactory.close();
for (ListIterator iterator = users.listIterator(); iterator.hasNext(); ) {
User user = (User) iterator.next();
System.out.println(user.getName() +
"\n\tAge: " + user.getAge() +
"\n\tSex: " + user.getSex());
}
}
} | 这个程序执行的结果范例如下,您可以看看实际上执行了哪些SQL:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, ser0_.age as age from USER user0_
justin
Age: 28
Sex: M
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F
Hibernate: update USER set name=?, sex=?, age=? where user_id=?
Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, ser0_.age as age from USER user0_
caterpillar
Age: 28
Sex: M
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F | Hibernate提供了一个saveOrUpdate()方法,为数据的储存或更新提供了一个统一的操作接口,藉由定义映像文件时,设定标签的unsaved-value来决定什么是新的值必需,什么是已有的值必须更新: User.hbm.xml
#p# unsaved-value 可以设定的值包括: ◆any - 总是储存 ◆none - 总是更新 ◆null - id为null时储存(预设) ◆valid - id为null或是指定值时储存 这样设定之后,您可以使用session.saveOrUpdate(updated);来取代上一个程序的session.update(updated);方法。 如果要删除数据,只要使用delete()方法即可,直接看个例子。 HibernateTest.java
import onlyfun.caterpillar.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import java.util.*;
public class HibernateTest {
public static void main(String[] args) throws HibernateException {
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
List users = session.find("from User");
User updated = null;
for (ListIterator iterator = users.listIterator(); iterator.hasNext(); ) {
User user = (User) iterator.next();
if(updated == null)
updated = user;
System.out.println(user.getName() +
"\n\tAge: " + user.getAge() +
"\n\tSex: " + user.getSex());
}
session.delete(updated);
users = session.find("from User");
session.close();
sessionFactory.close();
for (ListIterator iterator = users.listIterator(); iterator.hasNext(); ) {
User user = (User) iterator.next();
System.out.println(user.getName() +
"\n\tAge: " + user.getAge() +
"\n\tSex: " + user.getSex());
}
}
} | 一个执行的结果范例如下:
log4j:WARN No appenders could be found for logger (net.sf.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, ser0_.age as age from USER user0_
justin
Age: 28
Sex: M
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F
Hibernate: delete from USER where user_id=?
Hibernate: select user0_.user_id as user_id, user0_.name as name, user0_.sex as sex, ser0_.age as age from USER user0_
momor
Age: 25
Sex: F
Bush
Age: 25
Sex: M
Becky
Age: 35
Sex: F
User user = (User) session.load(User.class, id); | Hibernate对于数据的更新、删除等动作,是依赖id值来判定,如果您已知id值,则可以使用load()方法来加载资料。这边我们先介绍的是一些简单的查询动作,将来有机会的话,再介绍一些进阶的查询,如果您想要先认识一些HQL,可以看看参考手册的第11章,当中对于HQL有详细的说明。 转载自:http://www.51cto.com/specbook/229/34123.htm |