Hibernate学习之六-------Session,Query

一.Session  

1.Session介绍,作用,使用

 

The main runtime interface between a Java application and Hibernate. This is the central API class abstracting the notion of a persistence service.

The lifecycle of a Session is bounded by the beginning and end of a logical transaction. (Long transactions might span several database transactions.)

The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes.

 

Session设计是非线程安全的,也就是说一个Session实例同时只可由一个线程使用,同一个Session实例的多线程的并发调用将会引发难以预知的错误。

 

A typical transaction should use the following idiom:

 Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
     ...
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }
 

If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs.

 

2.Session的方法

  • save
       新增名为“zhangsheng”的用户
       Tuser user = new Tuser();
       user.setName("zhangsheng");
       session.save(user);
    get cf load
  • get

    if there is no such persistent instance return null
  • load

    You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.
  • delete

    //假设T_user表中存在id=1的记录
    Tuser user = (Tuser)session.get(Tuser.class,new Integer(1));
    session.delete(user);

    //通过Query接口进行基于HQL删除操作
    String hql = "delete Tuser where id = 1";
    Query query = session.createQuery(hql);
    query.executeUpdate();
  • 通过Query接口进行数据查询:
    String hql = "from Tuser user where user.name like ?";
    Query query = session.createQuery(hql);
    List list = query.list();
    Iterator it = list.iterator();
    while(it.hasNext()){
      Tuser user = (Tuser)it.next();
      System.out.println(user.getName());
    }
  • 通过Criteria接口进行数据查询:
    Criteria criteria = session.createCriteria(Tuser.class);
    criteria.add(Expression.eq("name","Cartier"));
    List list = criteria.list();
    Iterator it = list.iterator();
    while(it.hasNext()){
      Tuser user = (Tuser)it.next();
      System.out.println(user.getName());
    }

 

 Query和Criteria作为Hibernate数据查询接口,提供了对查询条件封装的机制,两者不同之处在于,Query面向HQL和Native SQL 而Criteria则提供了面向对象的查询模式。

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值