Hibernate综述
Hibernate框架用于实现对数据库的操作,为应用程序构建一个持久层。Hibernate是对JDBC的封装,通过JDBC的DataBaseMetaData类和ResultSetMetaData类获取数据库表的字段名、类型、大小等相关信息。再结合Java的反射机制建立Java类与数据库表以Java对象与数据表中记录之间的关系。
Hibernate定义了以下对象状态(参考http://wiki.jikexueyuan.com/project/ssh-noob-learning/three-states.html)。
- Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).
- Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.
- Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.
瞬态、持久态和游离态中,只有持久态态既与Session关联又存在于数据库中,瞬态是Hibernate新建后对象所处的状态,如果使瞬态对象与Session关联并调用save方法,则瞬态对象转化为持久态对象。当Session对象close或者evict某个对象时,该对象从持久态转化为瞬态。