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

Example Analysis of Hibernate Framework in persistence layer ORM Framework

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

Share

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

This article mainly introduces the persistence layer ORM framework in the Hibernate framework example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian with you to understand.

Preface

The concept of hibernate:

Hibernate is an ormapping framework (ORM framework, fully automatic ORM framework)

Hibernate is a database operation framework, namely persistence layer framework.

Hibernate is an open source object-relational mapping framework, which encapsulates JDBC with very lightweight objects, so that Java programmers can use object programming thinking to manipulate the database at will (SQL statements are automatically generated by Hibernate based on objects). Hibernate can be used in any situation that uses JDBC, not only in the client program of Java, but also in the Web application of Servlet/JSP.

What are the advantages of Hibernate?

1. The Hibernate code is relatively simple.

2. Hibernate is an object-oriented operation.

3. The database of Hibernate is very mobile.

4. Hibernate's cache is world-class.

Second, the shortcomings of Hibernate

1. Cannot interfere with the generation of sql statements, so if in a project, if the optimization requirements for sql statements are relatively high, then it is not suitable to use hibernate

2. If there are tens of millions of data in a table, it is not suitable to use hibernate (because of the caching mechanism, it will put a large amount of data into the cache)

3. Hibernate is suitable for developing software with small and medium-sized enterprises.

4. Hibernate is not suitable for dealing with complex SQL.

Third, build the Hibernate project architecture.

Project catalog

1. Guide package in the first step

2. The second step is to write the configuration file of Hibernate

I use the Mysql database, if you use something else to change the data source driver information.

Com.mysql.jdbc.Driver jdbc:mysql://127.0.0.1:3306/MySql root root org.hibernate.dialect.OracleDialect true true

For dialect, please refer to the picture below and configure it according to the requirements of the project.

Step 3: write the persistence class (pojo class)

Package com.zrrd.vo;public class Dept {private Integer deptno; private String dname; private String loc; public Integer getDeptno () {return deptno;} public void setDeptno (Integer deptno) {this.deptno = deptno;} public String getDname () {return dname;} public void setDname (String dname) {this.dname = dname;} public String getLoc () {return loc } public void setLoc (String loc) {this.loc = loc;} / / Direct conversion, it looks convenient to @ Override public String toString () {return "Dept {" + "deptno=" + deptno + ", dname='" + dname +'\'+ ", loc='" + loc +'\'+'}' } public Dept () {super ();} public Dept (Integer deptno, String dname, String loc) {this.deptno = deptno; this.dname = dname; this.loc = loc;}}

4. Step 4: write the Hibernate mapping file (* .hbm.xml)

This file completes the mapping between the persistent class and the specified table in the database. To put it bluntly, it means that the persistence class corresponds to which table in the database, and each property in the class corresponds to those fields in the database.

SEQ_DEPT

Step 5: write a test class to complete the operation on the database

Package com.zrrd.text;import com.zrrd.vo.Dept;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Text {public static void main (String [] args) {/ / read Hibernate.cfg.xml configuration file Configuration configuration=new Configuration (); configuration.configure ("hibernate.cfg.xml"); / / create sessionfactory project SessionFactory sessionFactory=configuration.buildSessionFactory () / / create Session objects Session session=sessionFactory.openSession (); / / create entity objects (vo objects corresponding to tables in the database are entity objects, and then operate the database (SQL statements are automatically created by Hibernate) Dept dept=session.get (Dept.class,1); System.out.println (dept); session.close (); sessionFactory.close ();}}

Execution result diagram

Data in stock

IV. Introduction of Hibernate core interface.

Hibernate has a total of six core interfaces, namely: Session, SessionFactory,

Transaction, Query, Criteria and Configuration. These six core interfaces will be used in any development. Through these interfaces, not only persistent objects can be accessed, but also transactions can be controlled.

1.Session

The Session interface is responsible for performing CRUD operations on persisted objects. (the task of CRUD is to communicate with the database and contains many common SQL statements.) . It is important to note, however, that Session objects are not thread safe. At the same time, the session of Hibernate is different from HttpSession in JSP applications. When the term session is used here, it actually refers to the session in Hibernate, and the HttpSession object will later be called the user session.

2.SessionFactory

The SessionFactory interface is responsible for initializing Hibernate. It acts as a proxy for the data storage source and is responsible for creating Session objects. Factory mode is used here. It is important to note that SessionFactory is not lightweight, because in general, a project usually requires only one SessionFactory, and when you need to operate on multiple databases, you can specify a SessionFactory for each database.

3.Transaction

The Transaction interface is an optional API, and you can choose not to use it and replace it with the underlying transaction code written by the designers of Hibernate. The Transaction interface is an abstraction of actual transaction implementations, including JDBC transactions, UserTransaction in JTA, and even CORBA transactions. The reason for this design is to enable developers to use a unified transaction interface, so that their projects can be easily ported between different environments and containers.

4.Query

The Query interface allows you to easily query databases and persistent objects, which can be expressed in two ways: HQL or SQL statements in the local database. Query is often used to bind query parameters, limit the number of query records, and finally perform query operations.

5.Criteria

The Criteria interface is very similar to the Query interface, allowing you to create and execute standardized object-oriented queries. It is worth noting that the Criteria interface is also lightweight and cannot be used outside of Session.

6.Configuration

The purpose of the Configuration interface is to configure Hibernate and start it. During the startup of Hibernate, an instance of the Configuration class first locates the mapping document, reads these configurations, and then creates a SessionFactory object. Although the Configuration interface plays only a small role in the entire Hibernate project, it is the first object encountered when starting hibernate.

5. Tool classes that encapsulate Hibernate

Of course, we certainly will not write the code in the test class when we CRUD in the actual development project, which will lead to a large amount of project code and poor portability, so we need to encapsulate and write a tool class, which can be called directly when we use it.

Public class HibernateUtil {/ / only one SessionFactory private static SessionFactory sessionFactory; is needed in a Hibernate container / / create SessionFactory objects using static code boxes static {/ / create Configuration objects Configuration conf = new Configuration (); / / load Hibernate configuration file conf.configure () / / load hibernate.cfg.xml under src by default / / create SessionFactory object sessionFactory = conf.buildSessionFactory ();} / get Session object public static Session getSession () {return sessionFactory.openSession ();} VI. Commonly used CRUD operations

I have written the relevant implementation methods, you just need to change the return type, just like the Jpa framework, you can use it directly in your project. Don't thank me too much to serve the people!

1. Query objects according to the primary key

Public Dept selectOne (int deptno) {Dept dept= null; / / get session object Session session = null; try {/ / get Session object session = HibernateUtil.getSession () / / get the corresponding information dept = (Dept) session.get (Dept.class, deptno) according to the primary key;} catch (Exception e) {e.printStackTrace () } finally {if (session! = null) {session.close ();}} return dept;}

two。 Query all the information

Public static List queryDept () {List deptList = null; / / declare session Session session= null; try {/ / create Session object session= HibernateUtil.getSession () / / declare HQL: where Dept is the entity class String hql= "from Dept"; / / write the class name after from / / get the Query object Query query = session.createQuery (hql) / / execute query deptList = query.list ();} catch (Exception e) {e.printStackTrace () } finally {if (session! = null) {session.close ();}} return deptList;}

3. Conditional query

Public List queryDeptByLoc (String loc) {List deptList = null; / / declare session Session session= null; try {/ / create Session object session= HibernateUtil.getSession () / / declare HQL: where Dept is the entity class String hql= "from com.zrrd.vo.Dept where loc=:loc"; / /: loc means parameter / / get query object Query query = session.createQuery (hql) / / assign query.setString ("loc", loc) to the parameter; / / assign a value to the specified parameter / / query returns List deptList = query.list () } catch (Exception e) {e.printStackTrace ();} finally {if (session! = null) {session.close () }} return deptList;}

4. Delete according to primary key

Public void deleteDept (int deptno) {/ / declare Session object Session session = null; try {/ / get Session object session = HibernateUtil.getSession () / / enable transaction protection Transaction ta = session.beginTransaction (); / / get the corresponding value Dept deleteObj = (Dept) session.get (Dept.class, deptno) according to id; / / delete the corresponding session.delete (deleteObj) / / commit transaction ta.commit ();} catch (Exception e) {e.printStackTrace () } finally {if (session! = null) {session.close ();}

5. Delete according to the specified condition

/ * * use Hql to delete * delete according to department number * / public int deleteDeptByLoc (String loc) {int result = 0; / / declare Session object Session session = null Try {/ / get Session object session = HibernateUtil.getSession (); / / enable transaction protection Transaction ta = session.beginTransaction () / / write the HQL to delete where: loc represents the parameter name String hql= "delete com.zrrd.vo.Dept where loc=:loc"; / / get the Query object Query query = session.createQuery (hql) / / assign the parameter query.setString ("loc", loc); / / execute the DML statement result = query.executeUpdate (); / / commit the transaction ta.commit () } catch (Exception e) {e.printStackTrace ();} finally {if (session! = null) {session.close () }} return result;}

6. Modify a single object

Public static void updateDept (Dept dept) {/ / declare Session object Session session = null; try {/ / get Session object session = HibernateUtil.getSession () / / enable transaction protection Transaction ta = session.beginTransaction (); / / modify session.update (dept) based on persistent object; / / commit transaction ta.commit () } catch (Exception e) {e.printStackTrace ();} finally {if (session! = null) {session.close () }

7. Modify according to conditions (HQL)

Public static int updateDeptLoc (String oldLoc,String newLoc) {int result = 0; / declare Session object Session session = null; try {/ / get Session object session = HibernateUtil.getSession () / / enable transaction protection Transaction ta = session.beginTransaction (); / / write HQL for deletion where: loc indicates the parameter name String hql= "update Dept set loc=:newLoc where loc=:oldLoc" / / get Query object Query query = session.createQuery (hql); / / assign query.setString ("newLoc", newLoc) to the parameter; query.setString ("oldLoc", oldLoc) / / execute DML statement result = query.executeUpdate (); / / commit transaction ta.commit ();} catch (Exception e) {e.printStackTrace () } finally {if (session! = null) {session.close ();}} return result;}

8. Store objects in the database

Public static void saveDept (Dept dept) {Session session = null; try {/ / get the Session object session = HibernateUtil.getSession (); / / get the transaction object Transaction ta = session.beginTransaction () / / storing persistent objects in database session.save (dept); / / committing transactions ta.commit ();} catch (Exception e) {e.printStackTrace () } finally {if (session! = null) {session.close ();} VII. Primary key generation mechanism

1. Increment: indicates that the plus mechanism of the database connected by the hibernate call generates information for the field (that is, the primary key)

2. Identity: it means that the self-adding mechanism is called by the connected data itself to generate information for the field (that is, to generate a primary key)

The difference between Increment and identity is that the former is called by hibernate, while the latter is called by the database itself (that is, you declare that the field is automatically incremented when you create the table). However, the above two primary key generation mechanisms are not applicable when connecting to Oracle. Because Oracle does not have an automatic add mechanism. If Oracle wants to use the automatic add-one mechanism, it must rely on.

3. Sequence: indicates that the field is generated by a sequence of data. If you do not want to specify a specific sequence, the sequence name in Oracle must be called HIBERNATE_SEQUENCE for default selection.

4. Uuid: generate the primary key information of 32-bit character type according to UUID algorithm.

5. Guid: use the sys_guid function provided by the database to generate the primary key. Note, however, that not all databases have sys_guid functions. So uuid is the first choice.

6. Native: select one from identity, sequence or hilo to generate the primary key according to the database to which you are connected. The applicable database is determined according to the selected generation method. (in this case, the database can be crossed because it can automatically select the generation scheme.) in Oracle, there must be a sequence called HIBERNATE_SEQUENCE.

Assigned: let the application assign values to the primary key itself. Note that the assignment must be done before calling the save () method. The applicable database is determined according to the selected generation method.

8. Types of Hibernate

In Hibernate, you can specify types using pure java types and Hibernate. The mapping of tables to Java types or Hibernate types can be done automatically within the Hibernate framework. It is recommended to use java type in development, which is more efficient.

Thank you for reading this article carefully. I hope the article "sample Analysis of Hibernate Framework in persistent layer ORM Framework" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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