In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
1 、 Configuration
Org.hibernate.cfg.Configuration is a configuration management class object.
1.1, configure ()
The method of loading the main configuration file (hibernate.cfg.xml), which loads src/hibernate.cfg.xml by default.
1.2, configure (String resource)
Config.configure ("cn/config/hibernate.cfg.xml"); loads the main configuration file with the specified name under the specified path
1.3The buildSessionFactory ()
Create a factory object for session
Configuration partial source code:
/ * * An instance of Configuration allows the application * to specify properties and mapping documents to be used when * creating a SessionFactory. Usually an application will create * a single Configuration, build a single instance of * SessionFactory and then instantiate Sessions in * threads servicing client requests. The Configuration is meant * only as an initialization-time object. SessionFactorys are * immutable and do not retain any association back to the * Configuration.
*
* A new Configuration will use the properties specified in * hibernate.properties by default. * * @ author Gavin King * @ see org.hibernate.SessionFactory * / public class Configuration implements Serializable {/ * * Use the mappings and properties specified in an application resource named hibernate.cfg.xml. * * @ return this for method chaining * * @ throws HibernateException Generally indicates we cannot find hibernate.cfg.xml * * @ see # configure (String) * / public Configuration configure () throws HibernateException {configure ("/ hibernate.cfg.xml"); return this } / * Use the mappings and properties specified in the given application resource. The format of the resource is * defined in hibernate-configuration-3.0.dtd. * * The resource is found via {@ link # getConfigurationInputStream} * * @ param resource The resource to use * * @ return this for method chaining * * @ throws HibernateException Generally indicates we cannot find the named resource * * @ see # doConfigure (java.io.InputStream String) * / public Configuration configure (String resource) throws HibernateException {log.info ("configuring from resource:" + resource) InputStream stream = getConfigurationInputStream (resource); return doConfigure (stream, resource);} / * * Create a {@ link SessionFactory} using the properties and mappings in this configuration. The * {@ link SessionFactory} will be immutable, so changes made to {@ code this} {@ link Configuration} after * building the {@ link SessionFactory} will not affect it * * @ return The build {@ link SessionFactory} * * @ throws HibernateException usually indicates an invalid configuration or invalid mapping information * / public SessionFactory buildSessionFactory () throws HibernateException {log.debug ("Preparing to build session factory with filters:" + filterDefinitions); secondPassCompile (); if (! MetadataSourceQueue.isEmpty () {log.warn ("mapping metadata cache was not completely processed");} enableLegacyHibernateValidator (); enableBeanValidation (); enableHibernateSearch (); validate (); Environment.verifyProperties (properties); Properties copy = new Properties () Copy.putAll (properties); PropertiesHelper.resolvePlaceHolders (copy); Settings settings = buildSettings (copy) Return new SessionFactoryImpl (this, mapping, settings, getInitializedEventListeners (), sessionFactoryObserver);}}
2 、 SessionFactory
Org.hibernate.SessionFactory
Session's factory (or represents the hibernate.cfg.xml profile)
The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
SessionFactory is an interface whose primary responsibility is to create Session instances. Typically, an application has only a single instance of SessionFactory, and different threads get an instance of Session from this SessionFactory.
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
The internal state of the SessionFactory is unchanged, that is, once the SessionFactory is created, its internal state will no longer change.
2.1and openSession ()
Create a sesison object
2.2, getCurrentSession ()
Create session or take out session object
SessionFactory partial source code:
/ * * The main contract here is the creation of {@ link Session} instances. Usually * an application has a single {@ link SessionFactory} instance and threads * servicing client requests obtain {@ link Session} instances from this factory. * * The internal state of a {@ link SessionFactory} is immutable. Once it is created * this internal state is set. This internal state includes all of the metadata * about Object/Relational Mapping. * * Implementors must be threadsafe. * * @ see org.hibernate.cfg.Configuration * * @ author Gavin King * @ author Steve Ebersole * / public interface SessionFactory extends Referenceable, Serializable {/ * * Open a {@ link Session}. * * JDBC {@ link Connection connection (s} will be obtained from the * configured {@ link org.hibernate.connection.ConnectionProvider} as needed * to perform requested work. * * @ return The created session. * * @ throws HibernateException Indicates a peroblem opening the session; pretty rare here. * / public org.hibernate.classic.Session openSession () throws HibernateException; / * * Obtains the current session. The definition of what exactly "current" * means controlled by the {@ link org.hibernate.context.CurrentSessionContext} impl configured * for use. * * Note that for backwards compatibility, if a {@ link org.hibernate.context.CurrentSessionContext} * is not configured but a JTA {@ link org.hibernate.transaction.TransactionManagerLookup} * is configured this will default to the {@ link org.hibernate.context.JTASessionContext} * impl. * * @ return The current session. * * @ throws HibernateException Indicates an issue locating a suitable current session. * / public org.hibernate.classic.Session getCurrentSession () throws HibernateException;}
Note: the return values of openSession () and getCurrentSession () are of type org.hibernate.classic.Session.
Org.hibernate.classic.Session is defined as follows:
Org.hibernate.classic.Session is defined as follows: / * An extension of the Session API, including all * deprecated methods from Hibernate2. This interface is * provided to allow easier migration of existing applications. * New code should use org.hibernate.Session. * @ author Gavin King * / public interface Session extends org.hibernate.Session {}
Org.hibernate.Session is defined as follows:
/ * 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. Instances may exist in one of three states:
*
* transient: never persistent, not associated with any Session
* persistent: associated with a unique Session
* detached: previously persistent, not associated with any Session
*
* Transient instances may be made persistent by calling save (), * persist () or saveOrUpdate (). Persistent instances may be made transient * by calling delete (). Any instance returned by a get () or * load () method is persistent. Detached instances may be made persistent * by calling update (), saveOrUpdate (), lock () or replicate (). * The state of a transient or detached instance may also be made persistent as a new * persistent instance by calling merge ().
*
* save () and persist () result in an SQL INSERT, delete () * in an SQL DELETE and update () or merge () in an SQL UPDATE. * Changes to persistent instances are detected at flush time and also result in an SQL * UPDATE. SaveOrUpdate () and replicate () result in either an * INSERT or an 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 (txshipping 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. * * @ see SessionFactory * @ author Gavin King * / public interface Session extends Serializable {/ * * 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.) This operation cascades to associated instances if the * association is mapped with cascade= "save-update". * * @ param object a transient instance of a persistent class * @ return the generated identifier * @ throws HibernateException * / public Serializable save (Object object) throws HibernateException; / * Update the persistent instance with the identifier of the given detached * instance. If there is a persistent instance with the same identifier, * an exception is thrown. This operation cascades to associated instances * if the association is mapped with cascade= "save-update". * * @ param object a detached instance containing updated state * @ throws HibernateException * / public void update (Object object) throws HibernateException; / * Either {@ link # save (Object)} or {@ link # update (Object)} the given * instance, depending upon resolution of the unsaved-value checks (see the * manual for discussion of unsaved-value checking). * This operation cascades to associated instances if the association is mapped * with cascade= "save-update". * * @ see Session#save (java.lang.Object) * @ see Session#update (Object object) * @ param object a transient or detached instance containing new or updated state * @ throws HibernateException * / public void saveOrUpdate (Object object) 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 is already associated * with the session, return that instance. This method never returns an uninitialized instance.) * * @ param clazz a persistent class * @ param id an identifier * @ return a persistent instance or null * @ throws HibernateException * / public Object get (Class clazz, Serializable id) throws HibernateException; / * Return the persistent instance of the given entity class with the given identifier, * assuming that the instance exists. This method might return a proxied instance that * is initialized on-demand, when a non-identifier method is accessed. *
* 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. * * @ param theClass a persistent class * @ param id a valid identifier of an existing persistent instance of the class * @ return the persistent instance or proxy * @ throws HibernateException * / public Object load (Class theClass, Serializable id) throws HibernateException;}
3 、 Session
Org.hibernate.Session
The session object maintains a connection (Connection) that represents the session connected to the database.
Hibernate's most important object: use only hibernate and database operations, using this object
3.1. Transaction
BeginTransaction () starts a transaction; hibernate requires that all operations with the database must have a transactional environment, otherwise an error will be reported!
3.2. Save and update
Save (Object object) saves an object
Update (Object object) updates an object
SaveOrUpdate (Object object) save or update method: do not set the primary key, perform the save; set the primary key, perform the update operation; if set the primary key there is no error!
Sample code:
Package com.rk.hibernate.a_hello;import java.util.Date;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test;public class App2 {private static SessionFactory sessionFactory; static {/ * * / / 1. Create the configuration management class object Configuration config = new Configuration (); / / load the configuration file * (load src/hibernate.cfg.xml by default) config.configure (); / / 2. * create the SessionFactory object sessionFactory = * config.buildSessionFactory () based on the loaded configuration management class object * / / create a SessionFactory object sessionFactory = new Configuration (). Configure (). BuildSessionFactory ();} / / 1. Save object @ Test public void testSave () {/ / object Employee emp = new Employee (); emp.setEmpName ("Zhang San"); emp.setWorkDate (new Date ()); / / create session object Session session = sessionFactory.openSession () according to the factory of session / / Open transaction Transaction transaction = session.beginTransaction (); / /-execute operation-session.save (emp); / / commit transaction transaction.commit (); / / close session.close () System.out.println ("execution is over!") ;} / 2. Update object @ Test public void testUpdate () {/ / object Employee emp = new Employee (); emp.setEmpId (20); emp.setEmpName ("Xiaoming"); / / create session Session session = sessionFactory.openSession () / / Open transaction Transaction tx = session.beginTransaction (); / / update. If id is not provided, an error is reported; if the id provided does not exist, error session.update (emp) is also reported; / / commit transaction tx.commit (); / / close session.close (); System.out.println ("execution ends!") ;} / 3. Save or update the object @ Test public void testSaveOrUpdate () {/ / object Employee emp = new Employee (); emp.setEmpId (3); emp.setEmpName ("Xiao Hong"); / / create session Session session = sessionFactory.openSession () / / Open transaction Transaction tx = session.beginTransaction (); / /-execute operation-/ / No primary key is set and save is performed. / / set the primary key and perform the update operation; if the primary key does not exist, an error will be reported! Session.saveOrUpdate (emp); / / commit transaction tx.commit (); / / close session.close (); System.out.println ("execution ends!") ;}}
3.3. Primary key query
Get (Class clazz, Serializable id) primary key query
Load (Class theClass, Serializable id) primary key query (lazy loading is supported)
Sample code:
@ Test public void testQuery () {Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction (); / / get primary key query Employee emp1 = (Employee) session.get (Employee.class, 2); System.out.println (emp1) / / load primary key query Employee emp2 = (Employee) session.load (Employee.class, 3); System.out.println (emp2); tx.commit (); session.close (); System.out.println ("execution ends!") ;}
3.4.Inquiry of HQL
The difference between HQL query and SQL query:
SQL: (structured query statement) queries tables (table) and fields (column); it is not case-sensitive.
HQL: hibernate query language is an object-oriented query language provided by hibernate, which queries objects and their property, and is case-sensitive.
Sample code:
/ / HQL query [suitable for database-based] @ Test public void testHQL () {Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction (); / / HQL query Query Q = session.createQuery ("From Employee where empId=2 or empId=3"); List list = q.list () System.out.println (list); tx.commit (); session.close (); System.out.println ("execution ends!") ;}
3. 5. Criteria query
Fully object-oriented query
Sample code:
/ / QBC query, query by criteria fully object-oriented query @ Test public void testQBC () {Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction (); Criteria criteria = session.createCriteria (Employee.class) / / conditional criteria.add (Restrictions.eq ("empId", 2)); List list = criteria.list (); System.out.println (list); tx.commit (); session.close (); System.out.println ("execution ends!") ;}
3.6. local SQL query
For complex queries, you can also use the original sql query, which is the support of local sql query! Disadvantages: can not cross the database platform!
Sample code:
/ / SQL @ Test public void testSQL () {Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction (); / / encapsulate each row of records as an array of objects and add them to the list collection / / SQLQuery sqlQuery = session.createSQLQuery ("select * from employee") / / encapsulate each row of records as the specified object type SQLQuery sqlQuery = session.createSQLQuery ("select * from employee") .addEntity (Employee.class); List list = sqlQuery.list (); System.out.println (list); tx.commit () Session.close (); System.out.println ("execution is over!") ;}
Complete sample code:
Package com.rk.hibernate.a_hello;import java.util.LinkedList;import java.util.List;import org.hibernate.Criteria;import org.hibernate.Query;import org.hibernate.SQLQuery;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.classic.Session;import org.hibernate.criterion.Restrictions;import org.junit.Test;public class App3 {private static SessionFactory sessionFactory Static {/ / create SessionFactory object sessionFactory = new Configuration () .configure () .buildSessionFactory ();} @ Test public void testQuery () {Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction () / / get primary key query Employee emp1 = (Employee) session.get (Employee.class, 2); System.out.println (emp1); / / load primary key query Employee emp2 = (Employee) session.load (Employee.class, 3); System.out.println (emp2); tx.commit () Session.close (); System.out.println ("execution is over!") ;} / / HQL query [suitable for database-based] @ Test public void testHQL () {Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction (); / / HQL query Query Q = session.createQuery ("From Employee where empId=2 or empId=3") List list = q.list (); System.out.println (list); tx.commit (); session.close (); System.out.println ("execution ends!") ;} / / QBC query, query by criteria fully object-oriented query @ Test public void testQBC () {Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction (); Criteria criteria = session.createCriteria (Employee.class) / / conditional criteria.add (Restrictions.eq ("empId", 2)); List list = criteria.list (); System.out.println (list); tx.commit (); session.close (); System.out.println ("execution ends!") ;} / / SQL @ Test public void testSQL () {Session session = sessionFactory.openSession (); Transaction tx = session.beginTransaction (); / / encapsulate each row of records as an array of objects and add them to the list collection / / SQLQuery sqlQuery = session.createSQLQuery ("select * from employee") / / encapsulate each row of records as the specified object type SQLQuery sqlQuery = session.createSQLQuery ("select * from employee") .addEntity (Employee.class); List list = sqlQuery.list (); System.out.println (list); tx.commit () Session.close (); System.out.println ("execution is over!") ;}}
4 、 Transaction
Org.hibernate.Transaction is a hibernate transaction object
A transaction is associated with a Session and is usually instantiated by a call to Session.beginTransaction ().
Transaction is associated with Session and is usually created by the Session.beginTransaction () method.
A single session might span multiple transactions since the notion of a session (a conversation between the application and the datastore) is of coarser granularity than the notion of a transaction. However, it is intended that there be at most one uncommitted Transaction associated with a particular Session at any time.
Session can be understood as a conversation between application and datastore. Multiple transactions are generated in a session, but there can be only one uncommitted transaction at a time.
Package org.hibernate;import javax.transaction.Synchronization;/** * Allows the application to define units of work, while * maintaining abstraction from the underlying transaction * implementation (eg. JTA, JDBC).
*
* A transaction is associated with a Session and is * usually instantiated by a call to Session.beginTransaction (). * A single session might span multiple transactions since * the notion of a session (a conversation between the application * and the datastore) is of coarser granularity than the notion of * a transaction. However, it is intended that there be at most one * uncommitted Transaction associated with a particular * Session at any time.
*
* Implementors are not intended to be threadsafe. * * @ see Session#beginTransaction () * @ see org.hibernate.transaction.TransactionFactory * @ author Anton van Straaten * / public interface Transaction {/ * Begin a new transaction. * / public void begin () throws HibernateException; / * Flush the associated Session and end the unit of work (unless * we are in {@ link FlushMode#MANUAL}. *
* This method will commit the underlying transaction if and only * if the underlying transaction was initiated by this object. * * @ throws HibernateException * / public void commit () throws HibernateException; / * * Force the underlying transaction to roll back. * * @ throws HibernateException * / public void rollback () throws HibernateException; / * * Was this transaction rolled back or set to rollback only? * * This only accounts for actions initiated from this local transaction. * If, for example, the underlying transaction is forced to rollback via * some other means, this method still reports false because the rollback * was not initiated from here. * * @ return boolean True if the transaction was rolled back via this * local transaction; false otherwise. * @ throws HibernateException * / public boolean wasRolledBack () throws HibernateException; / * * Check if this transaction was successfully committed. * * This method could return false even after successful invocation * of {@ link # commit}. As an example, JTA based strategies no-op on * {@ link # commit} calls if they did not start the transaction; in that case, * they also report {@ link # wasCommitted} as false. * * @ return boolean True if the transaction was (unequivocally) committed * via this local transaction; false otherwise. * @ throws HibernateException * / public boolean wasCommitted () throws HibernateException; / * * Is this transaction still active? * * Again, this only returns information in relation to the * local transaction, not the actual underlying transaction. * * @ return boolean Treu if this local transaction is still active. * / public boolean isActive () throws HibernateException; / * * Register a user synchronization callback for this transaction. * * @ param synchronization The Synchronization callback to register. * @ throws HibernateException * / public void registerSynchronization (Synchronization synchronization) throws HibernateException; / * * Set the transaction timeout for any transaction started by * a subsequent call to begin () on this instance. * * @ param seconds The number of seconds before a timeout. * / public void setTimeout (int seconds);}
5. Common problems
(1) ClassNotFoundException... ., missing jar file!
(2) if the program executes the program, hibernate also generates sql statements, but the data has no effect on the results. The general problem is that the transaction forgot to commit. . If you encounter a problem, you must read the wrong prompt!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.