Java interview--hibernate common face questions

Source: Internet
Author: User
Tags sessions
1, what is the hibernate of the concurrency mechanism. How to deal with concurrency problems.

Hibernate concurrency mechanism:

A, Hibernate session object is not thread-safe, for a single request, a single conversation, a single unit of work (that is, a single transaction, a single thread), it is usually used only once, and then discarded.

  If a session instance is allowed to be shared, those that support concurrency, such as HTTP request,session beans, will cause resource contention to occur. 

 If there are hibernate sessions in the HTTP session, there may be a synchronous access to HTTP synchronization. As long as the user clicks the browser's "refresh" quickly enough,  it will cause two concurrent threads to use the same session.  

b, multiple transactions concurrent access to the same resource, may cause the first class loss update, Dirty read, Phantom Read, not repeatable read, the second type of loss update a series of problems.

Solution: Set the transaction isolation level.
Serializable: Serialization. Highest Isolation Level
REPEATABLE READ: Repeatable READ
Read committed: Data has been submitted for reading
READ UNCOMMITTED: Data read not submitted. Worst Isolation Level
Set Lock: Optimistic lock and pessimistic lock.
Optimistic Lock: Use version number or timestamp to detect update loss, set optimistic-lock= "All" in the mapping to implement version checking without version or timestamp attribute mapping, at which point Hibernate will compare the status of each field record Row-Level pessimistic lock: Hibernate always uses the locking mechanism of the database and never locks objects in memory. Just specify the isolation level for the JDBC connection, and then let the database handle everything. Class Lockmode defines the different locking levels required for hibernate: Lockmode.upgrade,lockmode.upgrade_nowait,lockmode.read; 2, the difference between update and saveorupdate.

Update () and saveorupdate () are used to manage the status of the PO across sessions.
The object to be manipulated by the update () method must be a persisted object. That is, you cannot use the update () method if this object does not exist in the database.
An object that is manipulated by the Saveorupdate () method can either make persistent or render an object that is not persisted. If the object that is persisted is called saveorupdate (), the object in the database is updated, and if this method is used for an object that is not persisted, then the save to the database. 3. How to convert between the three states of Hibernate

When an object is save () by a transient state (Transient), it becomes a persistent state;
When we store objects in the session, we actually save a copy in the session map, which is a copy of the cache, and then a copy of the database, which is called a persistent object (persistent) in the cache. Session a close (), its cache is also closed, the entire session is invalidated, this time, this object into a Free State (Detached), but the database still exists.
When the Free State (Detached) update (), it becomes a persistent state (persistent).
When the persistent state (persistent) Delete () is changed to a transient state (Transient), there is no corresponding record in the database. 4. Compare the advantages and disadvantages of three kinds of hibernate search strategies

1 search immediately;
Benefits: fully transparent to the application, whether the object is in a persistent state or a free State, the application can easily navigate from one object to the object associated with it;
Disadvantages: Too many 1.select statements; 2. Objects that the application does not need to access can be loaded with wasted memory space;
2 Delayed Retrieval:
Benefits: The application determines which objects need to be loaded, avoids the execution of redundant SELECT statements, and avoids loading objects that the application does not need to access. Therefore, the retrieval performance can be improved and memory space can be saved.
Disadvantage: If the application wants to access the Free State proxy class instance, it must be guaranteed that he has been initialized in the persisted state;
3 Urgent left Outer connection search
Benefits: 1 Fully transparent to the application, regardless of whether the object is in a persistent state or a free State, the application can easily navigate an object to the object associated with it. 2 using outer joins, the number of SELECT statements is few;
Disadvantage: 1 May load objects that the application does not need to access, wasting a lot of memory space; 2 Complex database table connections can also affect retrieval performance; 5, how to see the SQL that hibernate builds and executes on the console

In the file applicationconfig.xml that defines the database and database properties, set the Hibernate.show_sql to True
The resulting SQL will appear on the console
Note: This will add to the burden on the system, which is not conducive to performance tuning 6, which caching policies are supported by Hibernate

Read-only: This strategy applies to data that is frequently read but not updated, which is by far the simplest and most efficient caching strategy
* Read/write: This strategy applies to data that needs to be updated and is more resource-intensive than read-only, where each transaction needs to be invoked in Session.close and Session.disconnect () in a JTA environment
* Nonstrict Read/write: This strategy does not guarantee that two concurrent transactions will modify the same piece of data, which applies to data that is often read but rarely updated
* Transactional: This strategy is a fully transactional cache strategy, can be used in JTA environment 7, hibernate inside the sorted collection and ordered collection what is the difference

Sorted collection is sorted in memory through the Java comparer
The ordered collection is the 8, hibernate, and why they are sorted in the database by ordering by.

1. Read and resolve configuration files
2. Read and parse mapping information, create Sessionfactory
3. Open Sesssion
4. Create Transaction Transation
5. Persistent operation
6. Submission of services
7. Close session
8. Close Sesstionfactory

Why to use:
1. The code for JDBC access to the database has been encapsulated, simplifying the cumbersome repetitive code of the data access layer.

Hibernate is a mainstream persistence framework based on JDBC and is an excellent ORM implementation. He simplifies the coding of the DAO layer to a large extent

Hibernate uses the Java reflection mechanism rather than the bytecode enhancement program to achieve transparency.

Hibernate's performance is very good because it is a lightweight framework. The flexibility of mapping is excellent. It supports a variety of relational databases, from one-to-one to many-to-many complex relationships. 10, Hibernate is how to delay loading?

When the hibernate is querying the data, the data does not exist in memory, when the program is actually operating on the data, the object exists and in memory, it realizes the delay loading, saves the memory cost of the server, and improves the performance of the server. 11, hibernate how to implement the relationship between classes? (eg: one-to-many, many-to-many Relationships)

The relationship between class and class is mainly embodied in the relationship between tables and tables, they operate on objects, and all the tables and classes in our program are mapped together by the Many-to-one, One-to-many, Many-to-many, 12 in the configuration file. , the next hibernate caching mechanism

Internal cache exists in Hibernate, also known as the first-level cache, which belongs to the Application object cache

Second-level caching:
A) application and caching
b) Distributed caching
Conditions: Data will not be modified by the third party, the data size in the acceptable range, the data update frequency is low, the same data is frequently used by the system, non-critical data
c The implementation of third party caching 13, Hibernate Query method

SQL, Criteria,objectcomposition
HQL:
1. Property Query
2, parameter query, named parameter query
3. Related Query
4, paging query
5, Statistical function 14, how to optimize hibernate.

1. Use bi-directional One-to-many Association, do not use one-way One-to-many
2. Flexible use of one-way One-to-many Association
3. No one-on-one, replace with multiple pairs
4. Configure object caching, do not use collection caching
5. A one-to-many set uses the bag, and Many-to-many sets use the Set
6. Inheritance class uses explicit polymorphism
7. A few table fields, tables association not afraid of more, there are two levels of cache backing 15, hibernate what kinds of query data in the way

3: HQL, conditional query QBC (queryby criteria), native SQL (established by createsqlquery) 16, talking about the role of hibernate in inverse

The inverse property defaults to false, meaning that both ends of the relationship maintain the relationship.
For example, student and teacher are many-to-many relationships, with an intermediate table teacherstudent maintenance. GP) I
If student this side inverse= "true", then the relationship is teacher on the other end, which means that when the student is inserted, the Teacherstudent table (the middle table) is not manipulated. Action on an intermediate table is triggered only when teacher is inserted or deleted. So it's wrong to inverse= "true" on both sides, causing any action to not trigger an effect on the middle table, which causes two relationships to be inserted in the middle table when both sides are inverse= "false" or default. 17. What are the benefits of Detached object (free objects)

Detached Object (free objects) can be passed to any layer until the presentation layer, rather than using any dto (DataTransfer Objects). Then you can also reassign the free object to another session. 18, the difference between JDBC hibernate and Ibatis

JDBC: Manual
Write SQL manually
Delete, insert, update to send the value of an object one by one out into SQL, you cannot pass directly to an object.
Select: Returns a resultset that is removed from one row, one field in the ResultSet, and then encapsulated into an object without returning an object directly.
Ibatis Features: Semi-automatic
SQL to manually write
Delete, insert, UPDATE: Pass directly to an object
Select: Return an object directly
Hibernate: Fully Automatic
Do not write SQL, automatic encapsulation
Delete, insert, UPDATE: Pass directly to an object
Select: Return directly to an object 19, in the database when the query speed is very slow, how to optimize?

1. Index Construction
2. Reduce the correlation between tables
3. Optimize SQL, try to make SQL quickly locate the data, do not let SQL do the full table query, should go to the index, the data large table in front
4. Simplify the query field, do not use the field, has been the control of return results, as far as possible to return a small number of data 20, what is sessionfactory, she is thread safe.

Sessionfactory is a hibrenate data store and thread-safe, so that multithreading can be accessed simultaneously. A sessionfactory can only be set up once when it is started. Sessionfactory should be packaged in a variety of cases so that it can be easily stored in an application code. 21, the Hibernate five core interface

Configuration Interface: Configure Hibernate to start Hibernate, create
Sessionfactory object,
Sessionfactory interface: Initialize Hibernate, Acting as the proxy for the data storage source, creating a
Session object, Sessionfactory is thread-safe, meaning that its same instance can be shared by multiple threads used by
, which is a heavyweight, level two cache;
Session Interface: Responsible for saving, updating, deleting, Load and query objects, which are thread insecure,
Avoid multiple threads sharing the same session, lightweight, first-level caching;
Transaction interface: administrative transactions;
Query and Criteria interfaces: Queries that execute a database.

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.