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 stubSession 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 exceptione.printStackTrace();if(ts!=null){ts.rollback();}throw new RuntimeException(e.getMessage());}finally{//关闭sessionif(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 stubSession 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 exceptione.printStackTrace();if(ts!=null){ts.rollback();}throw new RuntimeException(e.getMessage());}finally{//关闭sessionif(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();}//获取全新的全新的sesessionpublic static Session openSession(){return sessionFactory.openSession();}//获取和线程关联的sessionpublic 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'));

hibernate教程笔记4相关推荐

  1. Hibernate学习笔记(一)----针对不同的数据库不同的配置

    Hibernate初学笔记 l Hibernate初步配置: 1 新建项目 2 学习建立user-library-hibernate,并加入相应的jar包(hibernate核心jar包,lib下的所 ...

  2. hibernate学习笔记二

    上一篇关于hibernate学习笔记一,主要是作为hibernate的入门知识.没有和spring发生任何关系,这一篇我将把spring集成进去,看spring如何管理hibernate,还有和未使用 ...

  3. 台湾国立大学郭彦甫Matlab教程笔记(22) Cramer's method(Inverse matrix逆矩阵法)

    台湾国立大学郭彦甫Matlab教程笔记(22) Cramer's method(Inverse matrix) matrix left division左除:\ or mldivide() solvi ...

  4. 台湾国立大学郭彦甫Matlab教程笔记(21)linear equations(高斯消去法和追赶法)

    台湾国立大学郭彦甫Matlab教程笔记(21) today: linear equation 线性方程 linear system 线性系统 我们先看第一部分 linear equation 假定一个 ...

  5. 台湾国立大学郭彦甫Matlab教程笔记(20) root finding(numeric)

    台湾国立大学郭彦甫Matlab教程笔记(20) root finding(numeric) symbolic vs. numeric符号法和数值法的区别对比 symbolic 1)advantages ...

  6. 台湾国立大学郭彦甫Matlab教程笔记(17)numerical integration

    台湾国立大学郭彦甫Matlab教程笔记(17)numerical integration 数值积分 calculating the numerical value of a definite inte ...

  7. 台湾国立大学郭彦甫Matlab教程笔记(16) 数值微分 numerical differentiation

    台湾国立大学郭彦甫Matlab教程笔记(16) 数值微分 numeric differentiation 复习:diff()函数用来计算vector前后 entry的差异 数值微分继续 various ...

  8. 台湾国立大学郭彦甫Matlab教程笔记(15)polynomial integration 多项式积分

    台湾国立大学郭彦甫Matlab教程笔记(15) Polynomial integration多项式积分 一个多项式和它的积分如下 MATlAB中如何计算积分? polynomial integrati ...

  9. 台湾国立大学郭彦甫Matlab教程笔记(14)polynomial differentiation多项式微分

    台湾国立大学郭彦甫Matlab教程笔记(14) today: polynomial differentiation and integration多项式微分与积分 numerical differen ...

  10. 台湾国立大学郭彦甫Matlab教程笔记(12) advanced 2D plot 下

    台湾国立大学郭彦甫Matlab教程笔记(12) advanced 2D plot 下 上文记录的是关于统计的图标的绘制 下面我们来到另一个模块:颜色 fill()填充函数 功能:某一个封闭曲线,图上特 ...

最新文章

  1. 一个在菜场看到的,神一般的大爷!
  2. 转:iFire:玩聚 SRBacks 自定义脚本及样式表
  3. 本机镜像仓库base64解密
  4. Django 3.2.5博客开发教程:URL与视图函数
  5. android Json处理换行符
  6. 于小c三国语言_云顶之弈:三国成最强打工羁绊 校长教学顺滑转九五
  7. linux-tomcat-install
  8. 在用v-for时又想用v-if进行判断是否生产内容
  9. 获取div相对文档的位置
  10. modal verbs(一)
  11. python3.4连接mysql5.7数据库增删改查
  12. Centos5.8 安装 Redmine
  13. win7 计算机登录用户名和密码忘记,电脑win7登陆密码忘记了怎么办_win7忘记登陆密码如何进入-win7之家...
  14. 7-97 约会成功了吗
  15. 清华NLP组论文清单:全方位覆盖自然语言处理12大领域
  16. 树莓派Raspberry 4B+ 一篇快速搞定新版树莓派系统无屏幕初装+SSH连接+桌面显示
  17. 运用MATLAB批量读取excel表格
  18. npm、cnpm的安装
  19. 基于C++如何使用EGE做一个简单的坦克大战游戏
  20. Word操作之参考文献自动关联和引用

热门文章

  1. Delphi运行期错误
  2. pytorch与resnet(六) 预训练模型使用的场景
  3. 多项式曲线,分段曲线,曲线参数化,平面曲线,插值方法的样条曲线
  4. 数据-第18课-栈与递归
  5. 【运维安全】-sqlmap使用
  6. Ajax与Comet
  7. 《深入实践Spring Boot》阅读笔记之二:分布式应用开发
  8. VM安装CentOS6-相关NAT上网VM-tools安装
  9. 牢记31种CSS选择器
  10. #WP7 GPS# 如何判断GPS设备可用或者用户是否开启了GPS