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则提供了面向对象的查询模式。

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(设计模式,多线程,sql,Hibernate)