The most frequently studied points of knowledge integration in Hibernate interview

Source: Internet
Author: User
Tags connection pooling throw exception

For hibernate, the interviewer most want to know is the following summary of these more than 10 questions, each question has a detailed answer, if you are fully aware of the following questions, then asked about hibernate in the interview what are you afraid of? Let the confidence accompany your first sprint!

First, briefly describe the differences between Hibernate and JDBC, advantages and disadvantages?

JDBC has the advantage of JDBC flexibility over performance compared to hibernate. Hibernate has some advantages in easy learning and ease of use. JDBC has an advantage when it comes to many complex multi-table and complex database operations.
Same point:
Both are Java's database operations middleware.

Both objects that operate directly on the database are not thread-safe and need to be shut down in a timely manner.

Both can make explicit transactions on the database's update operations.

Different points:
Different SQL languages used: JDBC uses a relational database-based standard SQL language, Hibernate uses the HQL (Hibernate query Language) language

Different objects are manipulated: JDBC operates data, passes data directly to the database through SQL statements, and hibernate operates on persisted objects, which are updated to the database by the data of the underlying persisted object.

Data state is different: the data of the JDBC operation is "instantaneous", the value of the variable cannot be consistent with the value in the database, and the data of hibernate operation is durable, that is, the value of the persisted object's data property can be consistent with the value in the database.

JDBC and Hibernate read performance

1, JDBC is still the fastest way to access, whether it is a create or read operation, is JDBC fast.

2, Hibernate uses Uuid.hex constructs the primary key, the performance slightly somewhat loses, but is not big.

3. Create operation, JDBC is faster than hibernate using batch processing, and consumes JVM memory in batch mode much more than not using batch processing mode.

4, read the data, Hibernate iterator speed is very slow, because he is each next time to go to the database to fetch data, this point from observing the Task Manager Java process Memory changes can also be seen clearly, memory is dozens of k dozens of k increase.

5, read the data, Hibernate list speed quickly, because he is a one-time to take the data out, this point from observing the Task Manager Java process Memory changes can also be seen clearly, memory is almost 10M 10M increase.

6, the way JDBC read data and hibernate is the same as the list (it is very much related to the JDBC driver, different JDBC driver, the results will be very dissimilar), this from the observation of the Java process memory changes can be judged, Because JDBC does not need to construct a bunch of cat object instances like Hibernate, it takes up about half of the JVM's memory than Hibernate's list.

7, Hibernate's iterator way is not useless, it is suitable to select a small amount of data from a large result set, that does not need to occupy a lot of memory, but also can quickly get results. The iterator is also suitable for use with JCS buffering.

Additional instructions: In fact, regardless of cmp,hibernate,jdo and so on, all ORM is a JDBC package, CMP is a heavyweight package, JDO medium package, Hibernate is a lightweight package. In theory, ORM can never be better than JDBC performance. Just like any high-level language, running performance will never be better than assembly language.

For create and update operations, Hibernate will show more speed than JDBC because normal Java programmers do not necessarily use the functionality of JDBC batch.

For read operations, ORM generally has a double-layer buffer, that is, prepreadstatement Buffering and resultset buffering, and JDBC itself has no buffering mechanism, in the case of using connection pooling, Some connection pools will provide prepreadstatement buffering, some even provide resultset buffering, but in general, Java programmers generally do not consider optimizing buffering while writing JDBC, and this is not realistic, so in some cases The ORM will show more than the read speed of JDBC.

Two, hibernate three kinds of state distinction;

For hibernate, the object has three states, transient, persistent, detached
Transient: Transient or Free State (new Data ("not associated to session"), the instance of the PO is not associated with the session, and the instance of the PO is in transient)
Persistent: The persistence State (and the PO instance that is recorded in the database, that is, a record in the database table corresponds to this object.) Its state is persistent, and the objects obtained through get and load are all persistent)
Detached: off-tube or Free State
(1) When the PO object obtained by the Get or Load method is persistent, but if the delete (PO) is executed (but the transaction is not executed), the PO status is detached, (indicating and session out of association), A Free state due to delete can be persisted by Save or saveorupdate ()
(2) When a session executes close () or clear (), evict (), the Po object of persistent in the session cache becomes detached, at which point the persisted object becomes a de-tube object, and although the object has a database recognition value, However, it is not under the management of Hibernate persistence layer.

Iii. What is the difference between update () and Saveorupdate () in hibernate?

(1) Update () updates, no primary key will be error, saveorupdate () Save or update, no primary key to perform the insert.
(2) Update: is a transient (transient) or just off-pipe (detached) updates, for the Transient object update operation usually does not produce effect, for the de-tube object is a synchronous operation, that is, the database data changes and the object state is also a managed object
Saveorupdate: is also the operation of transient (transient) or just off-pipe (detached), whether inserted or updated, according to the specific conditions specified in the (identifier) ID, if the object does not persist identity ( Identifier) property, call Save () on it, or update () this object.
(3) If the PO object is already persisted in this session, execute Saveorupdate (PO) In this session do nothing
Throws a Nonuniqueobjectexception exception if Savaorupdate (the new PO for the given ID) has the same persistent identity (identifier) as another PO object associated with this session: a different object with the same identifier value is already associated with the session.

Four, Hibernate.update () and merge () difference?

As mentioned earlier, the basic merge and update are the same. However, if there is an instance of the same persistence identifier (identifier) in the session, the user-given object overrides the existing persisted instance of the session
(1) When we use update, we will throw an exception when we finish the execution.
(2) But when we use the merge, we copy the properties of the Po object A that handle the free State to the properties of the PO that is in the persistent state in the session, which is either persistent or persistent after execution, and we provide a or a free state.

V. Hibernate UPDATE and flush differences?

Hibernate update operates on an object that is in a free State or off-state (in a de-state due to the closing of the session), while flush is an object that operates in a persistent state.

By default, changes to a persistent state object (including the set container) do not require an update, as long as you change the value of the object, waiting for Hibernate flush to automatically update or save to the database.
(1) Call some queries and manually flush (), session closed, Sessionfactory closed combined. Get () An object that changes the properties of the object and closes the resource.
(2) Transaction commit (contains flush).

What is the difference between the load () and get () of Hibernate session?

1: If you use the Load method, Hibernate believes that the object (database record) corresponding to the ID must exist in the database, so it can be used with confidence, and it can use the proxy to delay loading the object. The database is queried for other property data in the object, but in case the record does not exist in the database, there is no way to throw an exception, and the Load method throw exception means that when the data for that object is used, the exception is thrown when the data in the database is not present, rather than when the object is created. Because the cache in the session is a fairly inexpensive resource for Hibernate, the session cache is checked at load to see if the object exists for that ID, and the proxy is created if it does not exist. So if you know that the ID must have a corresponding record in the database, you can use the Load method to implement lazy loading. For the Get method, hibernate confirms that the data exists for that ID, first in the session cache, then in the level two cache, and not in the database, which returns null ( There are many misconceptions on the internet that get to go to the database to find out at once not first check the session that is not correct, do not want to believe you go to do the test will know).

2, "get () will always return only the entity class", but in fact this is not correct, if the Get method is found in the session cache object corresponding to the ID, if the object is just before it was proxied, such as used by the Load method, or by other associated objects deferred loading, Then the returned proxy object, not the entity class object, if the proxy object has not yet loaded the Entity data (that is, other than the ID of the property data), then it will query the level two cache or the database to load the data, but the return is the proxy object, but the entity data has been loaded.

3, again pay attention to the description get method first query session cache, no query two cache, and finally query the database; Instead, the Load method first queries the session cache, does not create proxies, and queries two caches and databases when the data is actually used.

In short, for get and load the fundamental difference, in a word, hibernate for the load method that the data in the database must exist, can be assured that the use of agents to delay loading, if the use of the problem found in the process, can only throw exceptions, and for the Get method, Hibernate must obtain the actual data, otherwise null is returned.

Vii. Comparison of Hibernate list and iterator modes

(1), list mode is 1 times all the data into the memory, the construction of a large result set, the main time overhead is this step, this step of the time is far more than the JDBC and iterator way to construct the result set of the time overhead, and the memory cost is amazing And the traversal of the result set, the speed is very amazing (after testing, 300,000 recorded memory traversal of less than 100ms, because this step is not affected by JDBC, so the result is trustworthy). Therefore, the list method is suitable for repeated operations on the result set, such as paging, traversing backwards, jumping to the first row, jumping to the last line, and so on.

(2), the iterator method only takes the record ID into memory, and does not take all the data into memory, so the time overhead of constructing the result set is small, less than the JDBC and list methods, and the memory overhead is much smaller. In the case of the traversal of the result set, iterator still accesses the database, and all the major time overhead is spent here. As a result, the iterator approach is suitable for only 1 traversal operations on the result set, and the iterator approach is particularly well suited to taking small amounts of data from the very large result sets, which iterator performance is very good.

What is the role of Hibernate's inverse properties?

In hibernate, the term inverse is the meaning of inversion, in the association relationship, the inverse= "false" is the main control, which is responsible for maintaining the object's association relationship.
Inverse determines whether changes to the collection in the object are reflected in the database, so inverse only works on the collection, that is, only for One-to-many or many-to-many (because only these two associations contain collections. and one-to-one and Many-to-one only contain a reference to the other side, note that the general only in two-way association when you need to set inverse).
(1), one-to-many:
Usually in the one side to give up the maintenance of many relationships, so that the efficiency will be higher (such as the teacher remembers each student is a difficult thing, the efficiency is very low, so simply do not remember, this relationship by students to maintain, students remember a teacher is very easy)
So should be set on one side of the inverse=true, many of the parties set Inverse=false (more than one side can also not set the inverse property, because the default value is False), which indicates that the association is maintained by many Parties.
If one side maintains the relationship, it causes the object to update the "many" side of each object that is associated with the "one" when inserting or deleting the "a" side.
And if the "many" aspects of the maintenance relationship will not have an update operation, because the relationship is in the object of the multi-party, directly into the insertion or deletion of multiple objects on the line.
Obviously doing so will reduce the number of operations and improve efficiency.
Note: In a one-way One-to-many Association relationship, you cannot set inverse= "true" because there is no information for the master in the mapped file of the accused party.

(2), many-to-many: attributes are in separate tables. The default value of the inverse property is false. In a many-to-many association relationship, both ends of the relationship cannot be set to false, that is, the default is not inverse, and if it is set to false, the insert operation causes two relationships to be inserted in the relational table. Neither can be set to true, and if it is set to true, no action is triggered on the relational table. So set the inverse=true on either side and the other side inverse=false.

Ix. the role of Hibernate's Cascade attribute?

The purpose of the Cascade property is to describe the cascading nature of the associated object as it operates. Therefore, only the elements that relate to the relationship have the Cascade attribute.
Tags with cascade attributes include <many-to-one/> <one-to-one/> <any/> <set/><bag/> <idbag/> <l ist/> <array/>
Note: <ont-to-many/> and <many-to-many/> are used inside the collection tag, so the Cascade attribute is not required.
Cascade operation: Refers to whether the same action is performed on the associated party when the main control performs an operation.

What is the difference between lazy lazy loading under various related relationships?

1, one-to-one lazy loading
Lazy loading is not often a one-to-one, because lazy loading is designed to reduce the interaction with the database and thus improve execution efficiency, while in a single relationship, each data in the primary table is only for a database from the table, even if the query does not increase the cost of the interaction, and the main table cannot have contrained= True, so the primary table is not lazy to load. But from the table can have.
This lazy loading must satisfy three conditions on the same side of the object:
1, Lazy!=false (lazy properties have three options: No-proxy, False and proxy)
2, Constrained = true;
3, Fetch=select.

Note: Lazy loading is invalidated when fetch is set to join. Because fetch is a fetch, he has two values of select and join, and the default value is select. That is, when set to join, he will directly query from the table information to join instead of using the Select query again, resulting in lazy load invalidation.

2, One-to-many lazy loading
Unlike the one-to-one association, for One-to-many, each property of the main table will have more than one data from the table, and lazy loading is very effective at this time. For example, a department has a number of employees, if not lazy loading, each query this department will query out multiple employees, which will greatly increase the cost of interaction with the database. So hbernate default is to join lazy loading. This is why a persistentindexed* type object is returned when the collection property is queried. The object is actually a proxy object. Of course, you can disable it in the mapping file by setting the Lazy property to false.
Hibernate defaults to One-to-many is lazy loading, but users can also cancel lazy loading operations:
One: Set lazy= "false";
Two: Set fetch= "Join".

This lazy loading must satisfy two conditions on the same side of the object:
1, Lazy!=false (lazy properties have three options: No-proxy, False and proxy)
2, Fetch=select.

3, Many-to-one lazy loading

The lazy loading of this association relationship is just as easy as one-to-one lazy loading, because the efficiency of execution is not very obvious. While many-to-one relationships are the same, in hibernate, lazy loading is the default. It is also important to note that lazy loading does not distinguish whether there are values in the collection properties, and even if there is no value, he still uses lazy loading.

This lazy loading must satisfy two conditions at a time from the object side
1, Lazy!=false (lazy properties have three options: No-proxy, False and proxy)
2, Fetch=select

4, Many-to-many lazy loading

The lazy loading of this association and the lazy loading of the one-to-many are very obvious to the efficiency of the program execution.
This lazy loading must satisfy two conditions on the same side of the object:
1, Lazy!=false (lazy properties have three options: No-proxy, False and proxy)
2, Fetch=select

Lazy-loaded objects are changed proxy objects, and when the corresponding object is not closed, access to the properties of these lazy-loaded objects (except GetID and GetClass) Hibernate initializes the agents, or uses hibernate.initalize (proxy) To initialize the proxy object, and when the session is closed, an exception is thrown when the lazy-loaded object is accessed.

What are the differences between lazy use in hibernate?

The duration of the lazy: only valid when the session is opened, and lazy when the session is closed.

The lazy policy can be used in:

<class> Label: can be value true/false

<property> tag, you can take the value True/false, this feature requires class enhancement

<set>/<list>, you can take a value of True/false/extra

<one-to-one>/<many-to-one> and other labels, can be value false/proxy/no-proxy

6.1 The difference between get and load:

Get does not support lazy loading, while load is supported.

When querying for data that does not exist in a particular database, GET returns NULL, while load throws an exception.

Deferred loading of Class 6.2:

Lazy= "True" in the Settings <class> tab, or leave the default (that is, do not configure the Lazy property)

If the property value of lazy is true, then the SQL statement is emitted only when the data is actually used when loading with the Load method, which can reduce the overhead of the system.
Note: The lazy attribute configured on the class label does not affect the associated object!!!

12. What is the difference between Ibatis and hibernate?

The same point: masking the underlying access details of the JDBC API, using our ability to access data without dealing with the JDBC API.
The JDBC API programming process is fixed, and SQL statements are mixed with Java code, often with a patchwork of SQL statements, and the details are cumbersome.
Ibatis Benefits: Masking The underlying access details of the JDBC API, separating the SQL statement from the Java code, providing the ability to automatically encapsulate the result set as a collection of entity objects and objects, queryForList returns a collection of objects, Returns a single object with queryForObject, and provides parameters that automatically pass the properties of an entity object to an SQL statement.

Hibernate is a fully automated ORM mapping tool that automatically generates SQL statements, Ibatis requires us to write SQL statements in XML configuration files, and hibernate is more responsible and powerful than the Ibatis feature. Because hibernate generates SQL statements automatically, and we can't control the statement, we can't write a specific high-efficiency SQL. For some of the less complex SQL queries, hibernate can be very good for us to do, but for particularly complex queries, hibernate is difficult to adapt to, this time with Ibatis is a good choice, because ibatis or we write SQL statements.

13. Introduce Hibernate's level two cache

Answer according to the following ideas: (1) First of all to clarify what is the cache, (2) and then the hibernate session is a primary cache, that is, there is a cache, why there is a two-level cache, (3) and finally how to configure Hibernate's two-level cache.
(1) The cache is to save objects previously queried from the database and used in memory (a data structure), this data structure is usually or similar to HashMap, when you want to use an object in the future, the first query in the cache whether there is this object, if there is to use the object in the cache, If not, query the database and save the queried object in the cache for the next use. Here is the pseudo-code for the cache:
The second level cache of Hibernate is drawn, and the implementation principle of the cache is analyzed with the following pseudo code

Java code

Dao{hashmap map = new map (); User getUser (integer ID) {User User = Map.get (ID) if (user = = null) {user = Session.get (ID); Map.put (Id,user);} return user;}} Dao{cache cache = Nullsetcache (cache cache) {This.cache = Cache}user getUser (int id) {if (cache!=null) {User user = Cache.get (ID), if (user ==null) {user = Session.get (ID); Cache.put (Id,user);} return user;} return Session.get (ID);}}

(2) Hibernate session is a kind of cache, we usually call it hibernate cache, when you want to use the session from the database to query an object, the session is to see from their own internal existence of the object, the existence is directly returned, Does not exist to access the database and save the query's results inside itself. Since the session represents a conversation process, and the sessions are associated with a database connection, the session is best not to remain open for long periods of time, usually only for one transaction, and should be closed at the end of the transaction. And the session is thread insecure, and being shared by multiple threads is prone to problems. Usually only the global sense of the cache is the real cache application, there is a large cache value, therefore, hibernate session of this cache cache role is not obvious, the application is not very valuable. Hibernate's Level Two cache is a global cache configured for Hibernate, allowing multiple threads and multiple transactions to share this cache. We want a person to use it, others can use it, and the session doesn't have that effect.
(3) Level two caches are software parts that are independent of hibernate, products that belong to third parties, and multiple vendors and organizations provide caching products, such as Ehcache and Oscache, and so on. Using a level two cache in Hibernate, The first step is to configure which manufacturer's cache product to use in the Hibernate.cfg.xml configuration file, then configure the cache product's own configuration file, and finally configure which entity objects in Hibernate are to be included in the management of level two cache. Understanding the two-level caching principle and with this idea, it is easy to configure Hibernate's level two cache. Extended knowledge: A sessionfactory can be associated with a level two cache, or a level two cache can only be responsible for caching data in a database, when using Hibernate's Level two cache, Be careful not to have other apps or sessionfactory to change the data in the current database, so that the cached data will not be consistent with the actual data in the database.

Copyright notice: I feel like I'm doing a good job. I hope you can move your mouse and keyboard for me to order a praise or give me a comment, under the Grateful!_____________________________________________________ __ Welcome reprint, in the hope that you reprint at the same time, add the original address, thank you with

Integration of knowledge points most frequently explored in Hibernate interviews

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.