站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Hibernate 2.1.8 正式版 API 英文文档

Session (Hibernate API Documentation) - Hibernate 2.1.8 正式版 API 英文文档


net.sf.hibernate
Interface Session

All Superinterfaces:
Serializable
All Known Subinterfaces:
SessionImplementor
All Known Implementing Classes:
JCASessionImpl, SessionImpl

public interface Session
extends Serializable

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, find and delete operations for instances of mapped entity classes. Instances may exist in one of two states:

transient: not associated with any Session
persistent: associated with a Session

Transient instances may be made persistent by calling save(), update() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). Any instance returned by a find(), iterate() or load() method is persistent.

save() results in an SQL INSERT, delete() in an SQL DELETE and update() in an SQL UPDATE. Changes to persistent instances are detected at flush time and also result in an SQL UPDATE.

It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.

A Session instance is serializable if its persistent classes are serializable.

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.

Author:
Gavin King
See Also:
SessionFactory

Method Summary
 Transaction beginTransaction()
          Begin a unit of work and return the associated Transaction object.
 void cancelQuery()
          Cancel execution of the current query.
 void clear()
          Completely clear the session.
 Connection close()
          End the Session by disconnecting from the JDBC connection and cleaning up.
 Connection connection()
          Get the JDBC connection.
 boolean contains(Object object)
          Check if this instance is associated with this Session.
 Criteria createCriteria(Class persistentClass)
          Create a new Criteria instance, for the given entity class.
 Query createFilter(Object collection, String queryString)
          Create a new instance of Query for the given collection and filter string.
 Query createQuery(String queryString)
          Create a new instance of Query for the given query string.
 Query createSQLQuery(String sql, String[] returnAliases, Class[] returnClasses)
          Create a new instance of Query for the given SQL string.
 Query createSQLQuery(String sql, String returnAlias, Class returnClass)
          Create a new instance of Query for the given SQL string.
 void delete(Object object)
          Remove a persistent instance from the datastore.
 int delete(String query)
          Delete all objects returned by the query.
 int delete(String query, Object[] values, Type[] types)
          Delete all objects returned by the query.
 int delete(String query, Object value, Type type)
          Delete all objects returned by the query.
 Connection disconnect()
          Disconnect the Session from the current JDBC connection.
 void evict(Object object)
          Remove this instance from the session cache.
 Collection filter(Object collection, String filter)
          Apply a filter to a persistent collection.
 Collection filter(Object collection, String filter, Object[] values, Type[] types)
          Apply a filter to a persistent collection.
 Collection filter(Object collection, String filter, Object value, Type type)
          Apply a filter to a persistent collection.
 List find(String query)
          Execute a query.
 List find(String query, Object[] values, Type[] types)
          Execute a query with bind parameters.
 List find(String query, Object value, Type type)
          Execute a query with bind parameters.
 void flush()
          Force the Session to flush.
 Object get(Class clazz, Serializable id)
          Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.
 Object get(Class clazz, Serializable id, LockMode lockMode)
          Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.
 LockMode getCurrentLockMode(Object object)
          Determine the current lock mode of the given object.
 FlushMode getFlushMode()
          Get the current flush mode.
 Serializable getIdentifier(Object object)
          Return the identifier of an entity instance cached by the Session, or throw an exception if the instance is transient or associated with a different Session.
 Query getNamedQuery(String queryName)
          Obtain an instance of Query for a named query string defined in the mapping file.
 SessionFactory getSessionFactory()
          Get the SessionFactory that created this instance.
 boolean isConnected()
          Check if the Session is currently connected.
 boolean isDirty()
          Does this Session contain any changes which must be synchronized with the database? Would any SQL be executed if we flushed this session?
 boolean isOpen()
          Check if the Session is still open.
 Iterator iterate(String query)
          Execute a query and return the results in an iterator.
 Iterator iterate(String query, Object[] values, Type[] types)
          Execute a query and return the results in an iterator.
 Iterator iterate(String query, Object value, Type type)
          Execute a query and return the results in an iterator.
 Object load(Class theClass, Serializable id)
          Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.
 Object load(Class theClass, Serializable id, LockMode lockMode)
          Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.
 void load(Object object, Serializable id)
          Read the persistent state associated with the given identifier into the given transient instance.
 void lock(Object object, LockMode lockMode)
          Obtain the specified lock level upon the given object.
 void reconnect()
          Obtain a new JDBC connection.
 void reconnect(Connection connection)
          Reconnect to the given JDBC connection.
 void refresh(Object object)
          Re-read the state of the given instance from the underlying database.
 void refresh(Object object, LockMode lockMode)
          Re-read the state of the given instance from the underlying database, with the given LockMode.
 void replicate(Object object, ReplicationMode replicationMode)
          Persist all reachable transient objects, reusing the current identifier values.
 Serializable save(Object object)
          Persist the given transient instance, first assigning a generated identifier.
 void save(Object object, Serializable id)
          Persist the given transient instance, using the given identifier.
 void saveOrUpdate(Object object)
          Either save() or update() the given instance, depending upon the value of its identifier property.
 Object saveOrUpdateCopy(Object object)
          Copy the state of the given object onto the persistent object with the same identifier.
 Object saveOrUpdateCopy(Object object, Serializable id)
          Copy the state of the given object onto the persistent object with the given identifier.
 void setFlushMode(FlushMode flushMode)
          Set the flush mode.
 void update(Object object)
          Update the persistent instance with the identifier of the given transient instance.
 void update(Object object, Serializable id)
          Update the persistent state associated with the given identifier.
 

Method Detail

flush

public void flush()
           throws HibernateException
Force the Session to flush. Must be called at the end of a unit of work, before commiting the transaction and closing the session (Transaction.commit() calls this method). Flushing is the process of synchronising the underlying persistent store with persistable state held in memory.

Throws:
HibernateException

setFlushMode

public void setFlushMode(FlushMode flushMode)
Set the flush mode. The flush mode determines at which points Hibernate automatically flushes the session. For a readonly session, it is reasonable to set the flush mode to FlushMode.NEVER at the start of the session (in order to achieve some extra performance).

Parameters:
flushMode - the FlushMode
See Also:
FlushMode

getFlushMode

public FlushMode getFlushMode()
Get the current flush mode.

Returns:
FlushMode

getSessionFactory

public SessionFactory getSessionFactory()
Get the SessionFactory that created this instance.

See Also:
SessionFactory

connection

public Connection connection()
                      throws HibernateException
Get the JDBC connection. Applications are responsible for calling commit/rollback upon the connection before closing the Session.

Returns:
the JDBC connection in use by the Session
Throws:
HibernateException - if the Session is disconnected

disconnect

public Connection disconnect()
                      throws HibernateException
Disconnect the Session from the current JDBC connection. If the connection was obtained by Hibernate, close it or return it to the connection pool. Otherwise return it to the application.

This is used by applications which require long transactions.

Returns:
the connection provided by the application or null
Throws:
HibernateException - if the Session is disconnected
See Also:
reconnect()

reconnect

public void reconnect()
               throws HibernateException
Obtain a new JDBC connection. This is used by applications which require long transactions.

Throws:
HibernateException
See Also:
disconnect()

reconnect

public void reconnect(Connection connection)
               throws HibernateException
Reconnect to the given JDBC connection. This is used by applications which require long transactions.

Parameters:
connection - a JDBC connection
Throws:
HibernateException - if the Session is connected
See Also:
disconnect()

close

public Connection close()
                 throws HibernateException
End the Session by disconnecting from the JDBC connection and cleaning up. It is not strictly necessary to close() the Session but you must at least disconnect() it.

Returns:
the connection provided by the application or null
Throws:
HibernateException

cancelQuery

public void cancelQuery()
                 throws HibernateException
Cancel execution of the current query. May be called from one thread to stop execution of a query in another thread. Use with care!

Throws:
HibernateException

isOpen

public boolean isOpen()
Check if the Session is still open.

Returns:
boolean

isConnected

public boolean isConnected()
Check if the Session is currently connected.

Returns:
boolean

isDirty

public boolean isDirty()
                throws HibernateException
Does this Session contain any changes which must be synchronized with the database? Would any SQL be executed if we flushed this session?

Returns:
boolean
Throws:
HibernateException

getIdentifier

public Serializable getIdentifier(Object object)
                           throws HibernateException
Return the identifier of an entity instance cached by the Session, or throw an exception if the instance is transient or associated with a different Session.

Parameters:
object - a persistent instance
Returns:
the identifier
Throws:
HibernateException - if the Session is connected

contains

public boolean contains(Object object)
Check if this instance is associated with this Session.

Parameters:
object - an instance of a persistent class
Returns:
true if the given instance is associated with this Session

evict

public void evict(Object object)
           throws HibernateException
Remove this instance from the session cache. Changes to the instance will not be synchronized with the database. This operation cascades to associated instances if the association is mapped with cascade="all" or cascade="all-delete-orphan".

Parameters:
object - a persistent instance
Throws:
HibernateException

load

public Object load(Class theClass,
                   Serializable id,
                   LockMode lockMode)
            throws HibernateException
Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.

Parameters:
theClass - a persistent class
id - a valid identifier of an existing persistent instance of the class
lockMode - the lock level
Returns:
the persistent instance or proxy
Throws:
HibernateException

load

public Object load(Class theClass,
                   Serializable id)
            throws HibernateException
Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.

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

Parameters:
theClass - a persistent class
id - a valid identifier of an existing persistent instance of the class
Returns:
the persistent instance or proxy
Throws:
HibernateException

load

public void load(Object object,
                 Serializable id)
          throws HibernateException
Read the persistent state associated with the given identifier into the given transient instance.

Parameters:
object - an "empty" instance of the persistent class
id - a valid identifier of an existing persistent instance of the class
Throws:
HibernateException

replicate

public void replicate(Object object,
                      ReplicationMode replicationMode)
               throws HibernateException
Persist all reachable transient objects, reusing the current identifier values. Note that this will not trigger the Interceptor of the Session.

Parameters:
object - a transient instance of a persistent class
Throws:
HibernateException

save

public Serializable save(Object object)
                  throws HibernateException
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.)

Parameters:
object - a transient instance of a persistent class
Returns:
the generated identifier
Throws:
HibernateException

save

public void save(Object object,
                 Serializable id)
          throws HibernateException
Persist the given transient instance, using the given identifier.

Parameters:
object - a transient instance of a persistent class
id - an unused valid identifier
Throws:
HibernateException

saveOrUpdate

public void saveOrUpdate(Object object)
                  throws HibernateException
Either save() or update() the given instance, depending upon the value of its identifier property. By default the instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the identifier property mapping.

Parameters:
object - a transient instance containing new or updated state
Throws:
HibernateException
See Also:
save(java.lang.Object), update(Object object, Serializable id)

update

public void update(Object object)
            throws HibernateException
Update the persistent instance with the identifier of the given transient instance. If there is a persistent instance with the same identifier, an exception is thrown.

If the given transient instance has a null identifier, an exception will be thrown.

Parameters:
object - a transient instance containing updated state
Throws:
HibernateException

update

public void update(Object object,
                   Serializable id)
            throws HibernateException
Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent instance with the same identifier in the current session.

Parameters:
object - a transient instance containing updated state
id - identifier of persistent instance
Throws:
HibernateException

saveOrUpdateCopy

public Object saveOrUpdateCopy(Object object)
                        throws HibernateException
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved or does not exist in the database, save it and return it as a newly persistent instance. Otherwise, the given instance does not become associated with the session.

Parameters:
object - a transient instance with state to be copied
Returns:
an updated persistent instance
Throws:
HibernateException

saveOrUpdateCopy

public Object saveOrUpdateCopy(Object object,
                               Serializable id)
                        throws HibernateException
Copy the state of the given object onto the persistent object with the given identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If there is no database row with the given identifier, save the given instance and return it as a newly persistent instance. Otherwise, the given instance does not become associated with the session.

Parameters:
object - a persistent or transient instance with state to be copied
id - the identifier of the instance to copy to
Returns:
an updated persistent instance
Throws:
HibernateException

delete

public void delete(Object object)
            throws HibernateException
Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with existing persistent state.

Parameters:
object - the instance to be removed
Throws:
HibernateException

find

public List find(String query)
          throws HibernateException
Execute a query.

Parameters:
query - a query expressed in Hibernate's query language
Returns:
a distinct list of instances (or arrays of instances)
Throws:
HibernateException

find

public List find(String query,
                 Object value,
                 Type type)
          throws HibernateException
Execute a query with bind parameters. Bind a value to a "?" parameter in the query string.

Parameters:
query - the query string
value - a value to be bound to a "?" placeholder (JDBC IN parameter).
type - the Hibernate type of the value
Returns:
a distinct list of instances (or arrays of instances)
Throws:
HibernateException
See Also:
for access to Type instances

find

public List find(String query,
                 Object[] values,
                 Type[] types)
          throws HibernateException
Execute a query with bind parameters. Binding an array of values to "?" parameters in the query string.

Parameters:
query - the query string
values - an array of values to be bound to the "?" placeholders (JDBC IN parameters).
types - an array of Hibernate types of the values
Returns:
a distinct list of instances
Throws:
HibernateException
See Also:
for access to Type instances

iterate

public Iterator iterate(String query)
                 throws HibernateException
Execute a query and return the results in an iterator. If the query has multiple return values, values will be returned in an array of type Object[].

Entities returned as results are initialized on demand. The first SQL query returns identifiers only. So iterate() is usually a less efficient way to retrieve objects than find().

Parameters:
query - the query string
Returns:
an iterator
Throws:
HibernateException

iterate

public Iterator iterate(String query,
                        Object value,
                        Type type)
                 throws HibernateException
Execute a query and return the results in an iterator. Write the given value to "?" in the query string. If the query has multiple return values, values will be returned in an array of type Object[].

Entities returned as results are initialized on demand. The first SQL query returns identifiers only. So iterate() is usually a less efficient way to retrieve objects than find().

Parameters:
query - the query string
value - a value to be witten to a "?" placeholder in the query string
type - the hibernate type of value
Returns:
an iterator
Throws:
HibernateException

iterate

public Iterator iterate(String query,
                        Object[] values,
                        Type[] types)
                 throws HibernateException
Execute a query and return the results in an iterator. Write the given values to "?" in the query string. If the query has multiple return values, values will be returned in an array of type Object[].

Entities returned as results are initialized on demand. The first SQL query returns identifiers only. So iterate() is usually a less efficient way to retrieve objects than find().

Parameters:
query - the query string
values - a list of values to be written to "?" placeholders in the query
types - a list of Hibernate types of the values
Returns:
an iterator
Throws:
HibernateException

filter

public Collection filter(Object collection,
                         String filter)
                  throws HibernateException
Apply a filter to a persistent collection. A filter is a Hibernate query that may refer to this, the collection element. Filters allow efficient access to very large lazy collections. (Executing the filter does not initialize the collection.)

Parameters:
collection - a persistent collection to filter
filter - a filter query string
Returns:
Collection the resulting collection
Throws:
HibernateException

filter

public Collection filter(Object collection,
                         String filter,
                         Object value,
                         Type type)
                  throws HibernateException
Apply a filter to a persistent collection. A filter is a Hibernate query that may refer to this, the collection element.

Parameters:
collection - a persistent collection to filter
filter - a filter query string
value - a value to be witten to a "?" placeholder in the query string
type - the hibernate type of value
Returns:
Collection
Throws:
HibernateException

filter

public Collection filter(Object collection,
                         String filter,
                         Object[] values,
                         Type[] types)
                  throws HibernateException
Apply a filter to a persistent collection. Bind the given parameters to "?" placeholders. A filter is a Hibernate query that may refer to this, the collection element.

Parameters:
collection - a persistent collection to filter
filter - a filter query string
values - a list of values to be written to "?" placeholders in the query
types - a list of Hibernate types of the values
Returns:
Collection
Throws:
HibernateException

delete

public int delete(String query)
           throws HibernateException
Delete all objects returned by the query. Return the number of objects deleted.

Parameters:
query - the query string
Returns:
the number of instances deleted
Throws:
HibernateException

delete

public int delete(String query,
                  Object value,
                  Type type)
           throws HibernateException
Delete all objects returned by the query. Return the number of objects deleted.

Parameters:
query - the query string
value - a value to be witten to a "?" placeholder in the query string.
type - the hibernate type of value.
Returns:
the number of instances deleted
Throws:
HibernateException

delete

public int delete(String query,
                  Object[] values,
                  Type[] types)
           throws HibernateException
Delete all objects returned by the query. Return the number of objects deleted.

Parameters:
query - the query string
values - a list of values to be written to "?" placeholders in the query.
types - a list of Hibernate types of the values
Returns:
the number of instances deleted
Throws:
HibernateException

lock

public void lock(Object object,
                 LockMode lockMode)
          throws HibernateException
Obtain the specified lock level upon the given object. This may be used to perform a version check (LockMode.READ), to upgrade to a pessimistic lock (LockMode.UPGRADE), or to simply reassociate a transient instance with a session (LockMode.NONE).

Parameters:
object - a persistent or transient instance
lockMode - the lock level
Throws:
HibernateException

refresh

public void refresh(Object object)
             throws HibernateException
Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances. For example
  • where a database trigger alters the object state upon insert or update
  • after executing direct SQL (eg. a mass update) in the same session
  • after inserting a Blob or Clob

Parameters:
object - a persistent or transient instance
Throws:
HibernateException

refresh

public void refresh(Object object,
                    LockMode lockMode)
             throws HibernateException
Re-read the state of the given instance from the underlying database, with the given LockMode. It is inadvisable to use this to implement long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.

Parameters:
object - a persistent or transient instance
lockMode - the lock mode to use
Throws:
HibernateException

getCurrentLockMode

public LockMode getCurrentLockMode(Object object)
                            throws HibernateException
Determine the current lock mode of the given object.

Parameters:
object - a persistent instance
Returns:
the current lock mode
Throws:
HibernateException

beginTransaction

public Transaction beginTransaction()
                             throws HibernateException
Begin a unit of work and return the associated Transaction object. If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction. The class of the returned Transaction object is determined by the property hibernate.transaction_factory.

Returns:
a Transaction instance
Throws:
HibernateException
See Also:
Transaction

createCriteria

public Criteria createCriteria(Class persistentClass)
Create a new Criteria instance, for the given entity class.

Parameters:
persistentClass -
Returns:
Criteria

createQuery

public Query createQuery(String queryString)
                  throws HibernateException
Create a new instance of Query for the given query string.

Parameters:
queryString - a Hibernate query
Returns:
Query
Throws:
HibernateException

createFilter

public Query createFilter(Object collection,
                          String queryString)
                   throws HibernateException
Create a new instance of Query for the given collection and filter string.

Parameters:
collection - a persistent collection
queryString - a Hibernate query
Returns:
Query
Throws:
HibernateException

getNamedQuery

public Query getNamedQuery(String queryName)
                    throws HibernateException
Obtain an instance of Query for a named query string defined in the mapping file.

Parameters:
queryName - the name of a query defined externally
Returns:
Query
Throws:
HibernateException

createSQLQuery

public Query createSQLQuery(String sql,
                            String returnAlias,
                            Class returnClass)
Create a new instance of Query for the given SQL string.

Parameters:
sql - a query expressed in SQL
returnAlias - a table alias that appears inside {} in the SQL string
returnClass - the returned persistent class

createSQLQuery

public Query createSQLQuery(String sql,
                            String[] returnAliases,
                            Class[] returnClasses)
Create a new instance of Query for the given SQL string.

Parameters:
sql - a query expressed in SQL
returnAliases - an array of table aliases that appear inside {} in the SQL string
returnClasses - the returned persistent classes

clear

public void clear()
Completely clear the session. Evict all loaded instances and cancel all pending saves, updates and deletions. Do not close open iterators or instances of ScrollableResults.


get

public Object get(Class clazz,
                  Serializable id)
           throws HibernateException
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. (If the instance, or a proxy for the instance, is already associated with the session, return that instance or proxy.)

Parameters:
clazz - a persistent class
id - an identifier
Returns:
a persistent instance or null
Throws:
HibernateException

get

public Object get(Class clazz,
                  Serializable id,
                  LockMode lockMode)
           throws HibernateException
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. Obtain the specified lock mode if the instance exists.

Parameters:
clazz - a persistent class
id - an identifier
lockMode - the lock mode
Returns:
a persistent instance or null
Throws:
HibernateException