JPA, Hibernate, JdbcTemplate (recommended) difference

Source: Internet
Author: User
Tags reflection stmt

Hibernate batch processing of mass in fact from the performance considerations, it is very undesirable, waste a lot of memory. From its mechanism, hibernate it is first to identify the eligible data, put in memory, and then operate. The actual use of performance is very unsatisfactory.

Spring JdbcTemplate and Hibernate are essentially the same efficiency when dealing with simple query operations, and even the hibernate efficiency is slightly higher. However, when performing bulk operations, cumbersome operations, hibernate efficiency can reach spring jdbctemplate 80% is not bad. But hibernate can greatly improve the development efficiency, such as paging and other more complex development can be directly completed, so make up for the lack of efficiency.

To sum up: the pursuit of implementation efficiency is spring JDBC, the pursuit of development efficiency is hibernate;
If there are more bulk operations in the SQL statement, Spring JDBC is recommended.

If you really want to use hibernate, it should be used rationally, for example:

http://blog.csdn.net/abcd1101/article/details/64189755
1.Hibernate Relationship to JPA

JPA's overall thinking is broadly consistent with the existing ORM frameworks such as Hibernate, Toplink,jdo, and so on. JPA is a provider to achieve its functions, hibernate is a strong one in the JPA provider.

JPA is a specification, and Hibernate is one of its implementations. In addition to hibernate, there are eclipselink (once TopLink), OPENJPA and so on to choose from, so one of the benefits of using JPA is that you can replace the implementation without having to change too much code.

I want to put aside JPA, directly using hibernate annotation to define model, quickly found a few problems: JPA entity, Table,hibernate also have, but the content of different JPA have Column,onetomany, No hibernate, no substitutes.

I thought hibernate's support for JPA was another offering of a set of JPA-specific annotations, but it doesn't seem right now. Some important annotations such as column, Onetomany, etc., hibernate did not provide, indicating that the JPA annotation is already the core of hibernate, hibernate only provides some supplements, not two sets of annotations. If so, hibernate's support for JPA is sufficient, and we must use JPA to use hibernate annotations.

2. Why Choose JdbcTemplate

Reason 1:

I am in the development process of exposure to the persistence layer including Hibernate, MyBatis. Both of the persistence layer frames are not as satisfactory. First of all, the hibernate,hibernate to the database operation of the heavyweight package, so that the operation of the database is entirely object-oriented operations, where the object-oriented operation has become the gospel of many developers. But HQL is not so good, HQL is a simplified version of SQL, but HQL is after all a layer on the SQL, if one day your program in that piece of operation becomes unusually slow, then the HQL optimization will become more difficult, and hibernate the bottom of a large number of use of reflection mechanism, Although most of its reflection is performed when the program is initialized, the reflection mechanism exists during the program's operation. While MyBatis is a lightweight package for the persistence layer, in MyBatis, if you need to do an action, you first need to define the mapper and then define Mapper.xml. In Mapper.xml, the model mapping needs to be completed, and the interface-related SQL needs to be written, which the author considers to be a relatively large duplication of work. If you can write SQL directly in a Java class, and you can do simple object manipulation, then the program will have a bit of the hibernate part and a mybatis part. In future development, I will use the spring jdbctemplate for development.

The disadvantage of JdbcTemplate

JdbcTemplate development does not need to define so much XML, there is no HQL statement optimization difficult shortcomings, but there is a fatal problem, is too basic, based on the same as in the use of JDBC to operate. This seriously affects the efficiency of development. But it is also because of its very good foundation, so that its optimization is feasible.


Reason 2:

Hibernate batch update refers to the updating of mass data in a transaction, Hibernate bulk deletion means deleting a large amount of data in a transaction. The following program uses the Hibernate API to bulk update the age field for all records in the Customers table that are older than 0:
1. tx = Session.begintransaction ();
2. Iterator Customers=session.find ("from Customer C where c.age>0"). iterator ();
3. while (Customers.hasnext ()) {
4. Customer customer= (Customer) Customers.next ();
5. Customer.setage (Customer.getage () +1);
6.}
7. Tx.commit ();
8. Session.close ();
If there are 10,000 records in the Customers table that are older than 0, the find () method of the session loads 10,000 customer objects into memory at a draught. When the Tx.commit () method is executed, the cache is cleaned and hibernate executes the UPDATE statement for the 10,000 Update Customers table:
1. Update CUSTOMERS set age=? ... where id=i;
2. Update CUSTOMERS set age=? ... where id=j;
3. Update CUSTOMERS set age=? ... where id=k;
The above Hibernate batch Update method has two disadvantages:
(1) Consuming large amounts of memory, 10,000 customer objects must be loaded into memory before they are updated.
(2) The number of UPDATE statements executed is too large, each UPDATE statement can only update one customer object, must pass 10,000 update statements to update 10,000 customer objects, frequent access to the database, will greatly reduce the performance of the application.
To quickly release the memory occupied by 10,000 customer objects, you can immediately release its memory by calling the session's evict () method after each customer object is updated:
1. tx = Session.begintransaction ();
2. Iterator Customers=session.find ("from Customer C where c.age>0"). iterator ();
3. while (Customers.hasnext ()) {
4. Customer customer= (Customer) Customers.next ();
5. Customer.setage (Customer.getage () +1);
6. Session.flush ();
7. Session.evict (customer);
8.}
9. Tx.commit ();
Session.close ();
In the above program, after modifying the age attribute of a customer object, the Flush () method and the evict () method of the session are called immediately, and the flush () method enables hibernate to update the database immediately based on the state change of the Customer object To immediately execute the relevant UPDATE statement; the evict () method is used to purge the customer object from the cache, thereby releasing the memory it occupies in time.
However, the evict () method can only slightly improve the performance of bulk operations because, regardless of whether or not the evict () method is used, hibernate must execute 10,000 UPDATE statements to update 10,000 customer objects, which is an important factor affecting bulk operation performance. If hibernate can execute the following SQL statement directly:
1. Update CUSTOMERS set ageage=age+1 where age>0;
Then one of the update statements can update the 10,000 records in the Customers table. However, hibernate does not directly provide an interface to execute this UPDATE statement. The application must bypass the Hibernate API and execute the SQL statement directly through the JDBC API:
1. tx = Session.begintransaction ();
2. Connection con=session.connection ();
3. PreparedStatement stmt=con.preparestatement ("Update CUSTOMERS set ageage=age+1"
4. + "where age>0");
5. Stmt.executeupdate ();
6. Tx.commit ();
The above program demonstrates the process of bypassing the Hibernate API and accessing the database directly through the JDBC API. The application obtains the database connection used by the session through the connection () method of the session, and then creates the PreparedStatement object and executes the SQL statement through it. It is noteworthy that the application still declares the transaction boundary through the Hibernate transaction interface.
If the underlying database, such as Oracle, supports stored procedures, you can also perform hibernate bulk updates through stored procedures. Stored procedures run directly in the database and are faster. In an Oracle database, you can define a stored procedure named Batchupdatecustomer () with the following code:
1. Create or Replace procedure Batchupdatecustomer (p_age in number) as
2. Begin
3. Update CUSTOMERS set ageage=age+1 where age>p_age;
4. End;
The above stored procedure has a parameter p_age that represents the customer's age, and the application can invoke the stored procedure in the following ways:
1. tx = Session.begintransaction ();
2. Connection con=session.connection ();
3. String procedure = "{call Batchupdatecustomer (?)}";
4. CallableStatement cstmt = Con.preparecall (procedure);
5. Cstmt.setint (1,0); Set the age parameter to 0.
6. Cstmt.executeupdate ();
7. Tx.commit ();
As you can see from the above program, the application must also bypass the Hibernate API to invoke the stored procedure directly through the JDBC API.
The update () method of the various overloaded forms of the session can update only one object at a time, while some overloaded forms of the Delete () method allow HQL statements as arguments, such as:
1. Session.delete ("from Customer C where c.age>0");
If there are 10,000 records in the Customers table that are older than 0, the above code can delete 10,000 records. But the session's delete () method does not execute the following DELETE statement
1. Delete from CUSTOMERS where age>0;
The session's Delete () method loads 10,000 customer objects into memory first through the following SELECT statement:
1. Select * FROM CUSTOMERS where age>0;
Next, execute the 10,000 DELETE statement, deleting the Customer object individually:
1. Delete from CUSTOMERS where id=i;
2. Delete from CUSTOMERS where id=j;
3. Delete from CUSTOMERS where id=k;
This shows that directly through the Hibernate API for Hibernate batch update and Hibernate bulk deletion is not recommended. Using the JDBC API directly to execute related SQL statements or call related stored procedures is the best way to hibernate batch updates and hibernate bulk deletions, both of which have the following advantages:
(1) Do not need to load the bulk of the data in the database into memory, and then update or modify them individually, so do not consume a lot of memory.
(2) can update or delete large quantities of data in an SQL statement.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.