Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What does the important technology of Hibernate mean?

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you what the important technology of Hibernate refers to. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Hibernate technology has a lot to learn. Here we mainly introduce some powerful functions of Hibernate technology, including Hibernate technology development process and so on.

Hibernate technology development process:

1. Configuration file:

@ .properties format

@ .xml format (commonly used hibernate.cfg.xml) (placed under src or under wen-inf\ classes)

SessionFactory sf=new Configuration (). Configure (). BuildSessionFactory (); or SessionFactory sf=new Configuration (). Configure ("db.cfg.xml"). BuildSessionFactory ()

two。 Write a mapping file:

For example: the compilation of User.hbm.xml mapping files has a lot of content, which can be automatically generated according to the relevant mapping files, so we will not introduce them here.

3. Write persistence class:

For example: User.java

4. Write the HibernateSessionFactory class before writing DAO

Package com.wuxiaoxiao.hibernate; import org.hibernate.Session; import org.hibernate.HibernateException; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory {private static final String CONFIG_FILE_LOCATION= "/ hibernate.cfg.xml"; private static final ThreadLocal threadLocal=new ThreadLocal (); private static final Configuration cfg=new Configuration (); private static org.hibernate.SessionFactory sessionFactory; / / get session public static Session currentSession () throws HibernateException {Session session=threadLocal.get () If (session==null) {if (sessionFactory==null) {try {cfg.configuration (CONFIG_FILE_LOCATION); sessionFactory=cfg.buildSessionFactory ();} catch (Exception e) {System.err.println ("%% Error Creating SessionFactory%"); e.printStackTrace ();}} session=sessionFactory.openSession (); threadLocal.set (session);} return session } / / close session public static void closeSession () throws HibernateException {Session session= (Session) threadLocal.get (); threadLocal.set (null); if (sessionkeeper null) session.close ();}}

ThreadLocal is a thread local variable that provides a copy of the variable value for each thread accessing it, so that each thread can change its own copy independently without conflicting with the copies of other threads. ThreadLocal has three main methods: initValue () initializes variable values, get (), and set (Object) examples:

Public class ConnectionFactory {private fianl String URL= "jdbc:mysql://localhsot/mysatabase"; private static ThreadLocal connectionHolder=new ThreadLocal () {public COnnection initValue () {try {return DriverManager.getConnection (URL);} catch (Exception e) {}}; public Connection getConnection () {return connectionHolder.get ();}}

5. Write DAO for example:

Public User getUser (String username) throws HibernateException {Session session=null; Transaction tx=null; User user=null; try {session=HibernateSessionFactory.currentSession (); tx=session.beginTransaction (); Query query=session.createQuery ("from User where username=?"); query.setString (0meme username.trim ()); user= (User) query.uniqueResult (); query=null; tx.commit ();} catch (HibernateException e) {throw e;} finally {if (txnull null) tx.rollback (); HibernateSessionFactory.closeSession ();} return user }

6. Write service classes

Public boolean valid (String username,String password) {}

The following mainly describes the status of session manipulating database @ objects:

Hibernate defines and supports the following object states (state):

Instantaneous (Transient)-objects created by the new operator and not yet associated with the Hibernate Session are considered instantaneous (Transient). Instantaneous (Transient) objects are not persisted to the database, nor are they given a persistence identity (identifier). If the Transient object is not referenced in the program, it will be destroyed by the garbage collector (garbage collector). You can make it into a Persistent state using Hibernate Session. (Hibernate automatically executes the necessary SQL statements)

Persistent-an instance of persistence (Persistent) has a corresponding record in the database and has a persistence identity (identifier). An instance of Persistent may have just been saved or just loaded, either way, by definition, it exists within the associated Session scope. Hibernate detects any changes to objects in the Persistent state and synchronizes the object data (state) with the database (synchronize) when the current operation unit (unit of work) completes execution. Developers do not need to execute UPDATE manually. There is also no need to manually execute DELETE statements to change an object from a Persistent state to a Transient state.

Detached-there are records in the database, but not associated with session! When the Session associated with a Persistent object is turned off, the object becomes Detached. References to Detached objects are still valid, and objects can continue to be modified. If the Detached object is re-associated to a new Session, it will again become Persistent (changes during the Detached will be persisted to the database). This feature makes possible a programming model, that is, a long-running operation unit (unit of work) that gives the user time to think (user think-time). We call it an application transaction, which is an operation unit (unit of work) from the user's point of view.

@ use sve () to save the object to make it persistent

Session session=HibernateSessionFactory.currentSession (); User user=new User (); user.setName ("wuxiaoxiao"); user.setPassword (123456); session.save (user)

@ use load () to install in the object

User user= (User) session.load (User.class,new Integer (1))

If the object does not exist, an unrepairable exception will be thrown

@ use get () to install in the object

User user= (User) session.get (User.class,new Integer (4))

If the object does not exist, return null @ and use flush () to force the commit to refresh

User user= (User) session.get (User.class,new Integer (4)); user.setUsername ("ranran"); user.setPassword ("123456"); session.flush ()

Updates to user are in the same session and do not need to use update () or saveOrUpdate ()

@ remove persistent objects using delete ()

User user= (User) session.get (User.class,new Integer (4)); session.delete (user); session.flush ()

@ submit an object in a managed state using the update () method

Update () is used to update the corresponding persistent instance based on the tag of the given managed object instance! If you pass in a persistent object, the update () method is redundant. If you pass in an object in a temporary state, an error will occur unless you think that an id is temporarily assigned to the object. No matter what state of the object is passed in, there must be a record in the database that corresponds to the id of the object, otherwise an exception is thrown!

The object passed by @ saveOrUpdate () is updated if it exists in the database, otherwise it is inserted! He and update () mainly deal with managed state objects!

Use refresh () to force installation on an object, which is even more useful if triggers are used in the database to handle certain properties of the object!

Session.save (user); session.flush (); session.refresh (user)

Use Transaction to manage transactions

Example: as in the example of writing DAO above, use Query to do HQL query @ query without parameters

Query query=session.createQuery ("from User")

@ query with parameters

Query query=session.createQuery ("from User where username=:username"); query.setString ("username", "wuxiaoxiao"); or List names=new ArrayList (); names.add ("wuxiaoxiao"); names.add ("ranran"); Query query=session.createQuery ("from User where username in (: namelist)"); query.setParameterList ("namelist", names); or Query query=session.createQuery ("from User where username=?"); query.setSrting (0, "wuxiaoxiao")

@ get list result set

List list=query.list ()

@ get the iterative list result set

Iterator iterator1=query.iterator (); or Iterator iterator2=query.list () .iterator (); while (iterator.hasNext ()) User user= (User) iterator2.next ()

@ get an object

Query query=session.createQuery ("from User where username=?"); query.setString (0, "wuxiaoxiao"); User user= (User) query.uniqueResult ()

@ Scalar query

Iterator results = sess.createQuery ("select user.name,count (user.email) from User user" + "group by user.name") .list () .iterator (); while (results.hasNext ()) {Object [] row = (Object []) results.next (); String type = (String) row [0]; Integer count = (Integer) row [1] . }

@ paging query

Query Q = sess.createQuery ("from DomesticCat cat"); q.setFirstResult (20); q.setMaxResults (10); List cats = q.list ()

@ create a sql query

The above is what the important technology of Hibernate refers to. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report