After reading I guarantee you understand why a lot of people do not want to use the hibernate?

Personal blog navigation page (click on the right link to open a personal blog): Daniel take you on technology stack 

A, hibernate advantage

so you do not write sql hibernate, which can not only make your application more portable to other databases, but the main thing is to let the programmer concentrate more on business logic, data relationships, such as object-relational. hibernate for many, many relationships to achieve is very good. It is crucial that it supports lazy, you can make your data are loaded only when needed, that sounds perfect. hibernate there is a more cattle is HQL, it is entirely possible to query mapped to your OO model query language, and mybatis mapping, or a more convenient and more powerful than them.

1, What @ Lazy annotations are?

@Lazy notes that identifies whether the lazy bean, the source code is as follows:

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {
    /**
     * Whether lazy initialization should occur.
     */
    boolean value() default true;
}

Only one parameter, the default is true, that is to say as long as the addition of this comment is delayed loading.

2, @ Lazy how to use annotations

Not annotated before starting the main container will instantiate bean, as follows:

AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);

Create a user instance

And plus @Lazy comment you must load only the first time the following call:

@Scope
@Lazy
@Bean(value="user0",name="user0",initMethod="initUser",destroyMethod="destroyUser")
public User getUser(){
    System.out.println("创建user实例");
    return new User("张三",26);
}
AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(MainConfig.class);
User bean2 = applicationContext2.getBean(User.class);
创建user实例
实例1 === User [userName=张三, age=26]

@Lazy Annotation Annotation main function is to reduce the load time springIOC vessel started

Two, hibernate weaknesses

After reading advantage, hibernate feel omnipotent, and how lonely invincible Yes. Processing large amounts of data or large concurrency of network services not feel very good, so now beginning to talk about hibernate problems.

1, difficult to use some of the features of the database

hibernate and database developer isolated, developers do not need attention or Oracle database is MySQL, hibernate sql statement to help you generate queries, but the question is, if you want to use some sort of database-specific features, or make inquiries the sql full compliance with your mind, which is difficult. If you are using hibernate, although it can be customized for certain programs generate queries, but every bit of the feeling of boots scratching, and you develop them more pay. As support for the native sql hibernate, or quite perfect, this native sql can return non-managed entity, do not go cache hibernate, the optimization is to get, but if the entire project are so sharp, and that was with mybatis it.

In many cases, we have a demand: to get the current time of the database server. This is because the machine time and server time there is a difference. Various databases provide a function to obtain, for example, mysql, you can use "select now ()". hibernate also provides a function current_timestamp (Speaking timestamp, personally think that the poor timestamp of the database to do, actually, and datetime it is an order of magnitude (precision), which can be used to indicate how a real stamp ah!). However, you can not directly use the current time "select current_timestamp ()" to get the server, you must also add a table query! For example, "select current_timestamp () from tbl_Good ". Personal very depressed, I just want to use this function it simple, why do I have to know it inside the database table? ? ? ? Mention must also establish a mapping. . . . . .

I do not understand that this world is too complicated. Every kind of product are desperately complicated, in fact, they really ignored the average user requires only a small part of it. The default function should be able to meet the common needs of ordinary users, and is considered as a good product. I do not think hibernate done that.

2, can not meet the program requirements for the cache

Many web services, dependence cache is very large, hibernate built-in cache is supposedly very powerful, but still can not meet a lot of needs.

3, high coupling

indeed hibernate project development when you save a lot of time, but the extent of it your business logic model and database model dependent on each other too much. Nothing short-term problem, but with the changing of the project, which will change, when coupled only to maintain this relationship, you will find that your code is particularly vulnerable, just change a database schema, the entire project may have to change java dozens of times. And now mybatis automatic mapping is also doing well, being developed did not take long, and other projects at an advanced stage, you need a lot of customization and optimization of queries when mybatis development efficiency even more apparent.

4, debug difficult

As a back-end programmer, I like every line of code I know exactly doing it in the end. In particular database access code, system bottlenecks often arises in these places, each row can not be underestimated. I read an earlier version of hibernate part of the code, than I thought a lot of complex and powerful. Indeed many places Hibernate can only powerful line of code to solve a lot of problems, but for example, a update () or save () in the end did what, where both logic hibernate itself, but also the logic of your application, if this line had question, how do you do it? Personally, I think this is hard to do, and not like a fee to start something, this use mybatis.

As a programmer, I have always insisted that the code easier to change than change the configuration file.

5, hibernate update large quantities of data

(1) hibernate batch update all records age field is greater than zero customers table:

Transaction transaction = session.beginTransaction();     
Iterator customers=session.find("from Customer c where c.age>0").iterator();     
while(customers.hasNext()){     
    Customer customer=(Customer)customers.next();     
    customer.setAge(customer.getAge()+1);     
}      
transaction.commit();     
session.close();  

If the customers table has ten thousand records older than zero, then the session of the find () method will suddenly ten thousand customer objects loaded into memory. When performing tx.commit () method, it will clear the cache, hibernate customers to perform the update table update statement ten thousand:

update CUSTOMERS set AGE=? …. where ID=i;     

(2) The above batch updates hibernate mode has two drawbacks

  • Take up a lot of memory space, it must put ten thousand customer objects loaded into memory first, then 11 to update them.
  • Too many number of update statements executed, each update statement can only update a Customer object, you must update to ten thousand 10000 Customer object by update statement, frequent access to the database, it will greatly reduce the performance of the application.

(3) In order to quickly release the 10,000 occupied memory Customer object can be updated after each Customer object, it calls the Session evict () method to immediately release its memory:

Transaction transaction = session.beginTransaction();     
Iterator customers=session.find("from Customer c where c.age>0").iterator();     
while(customers.hasNext()){     
    Customer customer=(Customer)customers.next();     
    customer.setAge(customer.getAge()+1);     
    session.flush();     
    session.evict(customer);     
}      
transaction.commit();     
session.close();  

After the above procedure, modify the age property of a Customer object, you immediately call the Session flush () method and evict () method, flush () method enables hibernate immediately according to the state change of the Customer object synchronization update the database, thereby immediately implementation of the relevant update () statements; evict () method for this Customer object is purged from the cache, the timely release its occupied memory.

But evict () method can only slightly improve the performance of bulk operations, because with or without the use evict () method, Hibernate must perform 10000 update statement to update the 10000 Customer object, which is an important influence bulk operation performance factor. If Hibernate can directly execute the following SQL statement:

update CUSTOMERS set AGEAGE=AGE+1 where AGE>0;   

So more than one update statements can update 10,000 records CUSTOMERS table. However, Hibernate does not provide a direct interface to perform this update statement. Applications must be bypassed Hibernate API, directly to execute the SQL statements through JDBC API:

Transaction transaction = session.beginTransaction();     
Connection con=session.connection();     
PreparedStatement stmt=con.prepareStatement("update CUSTOMERS set AGEAGE=AGE+1 where AGE>0 ");     
stmt.executeUpdate();     
transaction.commit();  

The above procedure demonstrates bypassed Hibernate API, database access process directly through the JDBC API. Applications through the Session connection () method to obtain the use of the Session database connection, and then create PreparedStatement objects through it and execute SQL statements. It is worth noting that the application is still to declare the interface boundary affairs by the Hibernate Transaction. 
If the underlying database (such as Oracle) support for stored procedures, can also be performed through the Hibernate batch update stored procedure. Stored procedures run directly in the database, the speed is more accelerated. Can be defined in an Oracle database stored procedure called batchUpdateCustomer () code is as follows:

create or replace procedure batchUpdateCustomer(p_age in number) as     
begin     
update CUSTOMERS set AGEAGE=AGE+1 where AGE>p_age;     
end;  

Above stored procedure has a parameter p_age, on behalf of the customer's age, the application can call the stored procedure in the following manner:

Transaction transaction = session.beginTransaction();     
Connection con=session.connection();     
String procedure = "{call batchUpdateCustomer(?) }";     
CallableStatement cstmt = con.prepareCall(procedure);     
cstmt.setInt(1,0); //把年龄参数设为0     
cstmt.executeUpdate();     
transaction.commit();  

Seen from the above, the application must also be bypassed Hibernate API, directly via the JDBC API call the stored procedure. 

6, hibernate delete large amounts of data

Various forms of overloading Session of update () methods are only updated once a target, and some overloads delete () method allows HQL statement as a parameter, for example:

session.delete("from Customer c where c.age>0");  

If the CUSTOMERS table has 10,000 records older than zero, then the above code can be deleted ten thousand records. But Session's delete () method does not execute the following delete statement

delete from CUSTOMERS where AGE>0;  

Session's delete () method to the 10000 Customer object is loaded into memory by the following select statement:

select * from CUSTOMERS where AGE>0;  

The next statement is executed ten thousand delete, delete one by one Customer object:

delete from CUSTOMERS where ID=i;     
delete from CUSTOMERS where ID=j;     
delete from CUSTOMERS where ID=k;  

This can be seen by the perform batch updates Hibernate and Hibernate Hibernate API directly through the bulk deletion is not recommended. The implementation of the relevant SQL statements or stored procedure calls directly through the JDBC API, is the best way to hibernate batch updates and batch delete.

Su speak little warm Spring JdbcTemplate

Third, the sharp eyes of the masses, do not Guards and the line

 

Fourth, a number of insights after being sprayed

A feeling that denounced the General Assembly, I feel deeply ignorant of frustration, I really just want to learn it, I hope a few years later, I can not change the beginning of the heart.

As a junior programmer, there is no need to spend too much time to prove useless technology, I did not hibernate framework for in-depth study, but in some personal insights superficial level.

Framework itself does not say right or wrong, only not suitable, any framework has its own capabilities, hibernate encapsulates many useful API to us, reducing the difficulty and complexity of the operation of the database, while reducing the template code number, but left to hibernate developer of operational space relative mybatis a lot less; mybatis use more flexible framework, developers can customize the query, but increases the amount of template code, does not seem to hibernate border. Two frameworks in the convenient and flexible two indicators make trade-offs and compromises, which can not be said to be wrong framework. For a framework needs to have their own areas of focus and design vision, you can not cover everything, just like the big brother said:

Use any kind of technical framework, we need to fit the reality of the business needs as well as their technological capabilities. When you do not go in-depth understanding of a technical or business needs not fit with the current framework, do not blindly criticize the quality of the frame.

Attached Java / C / C ++ / machine learning / Algorithms and Data Structures / front-end / Android / Python / programmer reading / single books books Daquan:

(Click on the right to open there in the dry personal blog): Technical dry Flowering
===== >> ① [Java Daniel take you on the road to advanced] << ====
===== >> ② [+ acm algorithm data structure Daniel take you on the road to advanced] << ===
===== >> ③ [database Daniel take you on the road to advanced] << == ===
===== >> ④ [Daniel Web front-end to take you on the road to advanced] << ====
===== >> ⑤ [machine learning python and Daniel take you entry to the Advanced Road] << ====
===== >> ⑥ [architect Daniel take you on the road to advanced] << =====
===== >> ⑦ [C ++ Daniel advanced to take you on the road] << ====
===== >> ⑧ [ios Daniel take you on the road to advanced] << ====
=====> > ⑨ [Web security Daniel take you on the road to advanced] << =====
===== >> ⑩ [Linux operating system and Daniel take you on the road to advanced] << = ====

There is no unearned fruits, hope you young friends, friends want to learn techniques, overcoming all obstacles in the way of the road determined to tie into technology, understand the book, and then knock on the code, understand the principle, and go practice, will It will bring you life, your job, your future a dream.

Published 47 original articles · won praise 0 · Views 264

Guess you like

Origin blog.csdn.net/weixin_41663412/article/details/104898869