Query接口的使用
TestMain.java
package com.hsp.view;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Query;
import java.util.List;
import com.hsp.domain.Employee;
import com.hsp.utils.*;
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session=HibernateUtil.getCurrentSession();
Transaction ts=null;
try {
ts=session.beginTransaction();
//获取query引用【这里Employee不是表,而是domain类名】
//id指映射对象的属性的名称或者表的字段名称,建议使用类的属性名
Query query=session.createQuery("from Employee where id=1");
//通过list方法啊获得结果,这个list会自动封装成对应的domain对象
List<Employee> list=query.list();
for(Employee e:list){
System.out.println(e.getName()+" "+e.getHiredate());
}
ts.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(ts!=null){
ts.rollback();
}
throw new RuntimeException(e.getMessage());
}finally{
//关闭session
if(session!=null && session.isOpen()){
session.close();
}
}
}
}
Criteria接口使用
package com.hsp.view;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import java.util.List;
import com.hsp.domain.Employee;
import com.hsp.utils.*;
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session=HibernateUtil.getCurrentSession();
Transaction ts=null;
try {
ts=session.beginTransaction();
//获取query引用【这里Employee不是表,而是domain类名】
//id指映射对象的属性的名称或者表的字段名称,建议使用类的属性名,按id升序取出
Criteria cri=session.createCriteria(Employee.class).setMaxResults(2).addOrder(Order.asc("id"));
List<Employee> list=cri.list();
for(Employee e:list){
System.out.println(e.getId()+" "+e.getHiredate());
}
ts.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
if(ts!=null){
ts.rollback();
}
throw new RuntimeException(e.getMessage());
}finally{
//关闭session
if(session!=null && session.isOpen()){
session.close();
}
}
}
}
HibernateUtil.java
package com.hsp.utils;
import java.util.List
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {
private static SessionFactory sessionFactory=null;
//使用线程局部模式
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
private HibernateUtil(){};
static {
sessionFactory=new Configuration().configure().buildSessionFactory();
}
//获取全新的全新的sesession
public static Session openSession(){
return sessionFactory.openSession();
}
//获取和线程关联的session
public static Session getCurrentSession(){
Session session=threadLocal.get();
//判断是否得到
if(session==null){
session=sessionFactory.openSession();
//把session对象设置到 threadLocal,相当于该session已经和线程绑定
threadLocal.set(session);
}
return session;
}
//统一的一个修改和删除(批量 hql) hql"delete upate ...??"
public static void executeUpdate(String hql,String [] parameters){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
tx.commit();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
}
//统一的添加的方法
public static void save(Object obj){
Session s=null;
Transaction tx=null;
try {
s=openSession();
tx=s.beginTransaction();
s.save(obj);
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
//提供一个统一的查询方法(带分页) hql 形式 from 类 where 条件=? ..
public static List executeQueryByPage(String hql,String [] parameters,int pageSize,int pageNow){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize);
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
//提供一个统一的查询方法 hql 形式 from 类 where 条件=? ..
public static List executeQuery(String hql,String [] parameters){
Session s=null;
List list=null;
try {
s=openSession();
Query query=s.createQuery(hql);
//先判断是否有参数要绑定
if(parameters!=null&& parameters.length>0){
for(int i=0;i<parameters.length;i++){
query.setString(i, parameters[i]);
}
}
list=query.list();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
// TODO: handle exception
}finally{
if(s!=null&&s.isOpen()){
s.close();
}
}
return list;
}
}
Employee.java
package com.hsp.domain;
import java.io.Serializable;
//这是一个domain对象(实际上就是javabean/有些人pojo)
//他和Employee对应
public class Employee implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String email;
private java.util.Date hiredate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public java.util.Date getHiredate() {
return hiredate;
}
public void setHiredate(java.util.Date hiredate) {
this.hiredate = hiredate;
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- hibernate 设计者,给我们提供了一写常用的配置 -->
<!-- 配置使用的driver -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<!-- 配置dialect方言,明确告诉hibernate连接是哪种数据库 -->
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<!-- 显示出对于sql -->
<property name="show_sql">true</property>
<!-- 指定管理的对象映射文件 -->
<mapping resource="com/hsp/domain/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 用于配置domain对象和表的关系映射,为对象关系映射文件 -->
<hibernate-mapping package="com.hsp.domain">
<class name="Employee" table="employee">
<!-- id元素用于指定主键属性 -->
<id name="id" column="id" type="java.lang.Integer">
<!-- 该元素用于指定主键值生成策略hilo native increment sequence uuid -->
<generator class="sequence">
<param name="sequence">emp_seq</param>
</generator>
</id>
<!-- 对其它属性还有配置 -->
<property name="name" type="java.lang.String">
<column name="name" not-null="false" />
</property>
<property name="email" type="java.lang.String" >
<column name="email" not-null="false"/>
</property>
<property name="hiredate" type="java.util.Date">
<column name="hiredate" not-null="false" />
</property>
</class>
</hibernate-mapping>
--创建employe 表
create table employee(
id number primary key,
name varchar2(64) not null,
email varchar2(64) not null,
hiredate date not null);
--创建一个序列
create sequence emp_seq
start with 1
increment by 1
minvalue 1
nomaxvalue
nocycle
nocache
;
update employee set hiredate=to_date('2013-12-21','yyyy-mm-dd') where id=1;
insert into employee values(3,'关羽','guanyu@qq.com',to_date('2012-12-21','yyyy-mm-dd'));