Hibernate face Test

Source: Internet
Author: User

What is the concurrency mechanism for hibernate? How to deal with concurrency problems?
Hibernate concurrency mechanism:
A, Hibernate session object is non-thread-safe, for a single request, a single session, a single unit of work (that is, a single transaction, a single thread), it is usually used only once,
And then throw it away.
If a session instance allows sharing, those that support concurrent runs, such as HTTP request,session beans, will cause resource contention.
If you have hibernate session in the HTTP session, you may have synchronous access to the HTTP session. As long as the user clicks the browser's "refresh" fast enough,
Will cause two concurrently running threads to use the same session.
b, multiple transactions concurrently access the same piece of resources, may throw the first kind of lost updates, dirty read, Phantom Read, non-repeatable read, the second class lost update a series of problems.

   Solution: Set the transaction isolation level.
Serializable: Serialization. Highest isolation LEVEL
REPEATABLE READ: Repeatable read
Read Committed: Committed data read
READ UNCOMMITTED: UNCOMMITTED data read. The lowest isolation level
             set locks: optimistic and pessimistic locks.
             optimistic Lock: Use a version number or timestamp to detect the loss of the update, in The mapping of the optimistic-lock= "all" can be implemented without a version or timestamp attribute mapping, and hibernate will compare the status row-level pessimistic lock for each field of a row of records: Hibernate always uses the locking mechanism of the database, Never lock an object in memory! Just specify the isolation level for the JDBC connection, and then let the database take care of everything. The class Lockmode defines the different locking levels required for hibernate: Lockmode.upgrade,lockmode.upgrade_nowait,lockmode.read;

Several exceptions that often occur in 2.Hibernate and spring
Org.springframework.beans.factory.BeanCreationException:
Error creating Bean with Name ' sessionfactory ' defined in ServletContext resource [/web-inf/applicationcontext.xml]:
Initialization of Bean failed; Nested exception is org.hibernate.MappingException:Repeated column with mapping for entity: Com.xindeco.myregister.pojo.MyRegisterInfo column:
Password (should is mapped with insert= "false" Update= "false")
Cause of Error: Password and Repassword both correspond to the password column in the database table, and both update and insert are set to true. The XML file is as follows:

<property name= "Password"
Type= "Java.lang.String"
Update= "true"
Insert= "true"
Access= "Property"
column= "Password"
Length = "32"
/> <property name= "Repassword"
Type= "Java.lang.String"
Update= "false"
Insert= "false"
Access= "Property"
column= "Password"
Length = "32"
/>
WORKAROUND: Set Repassword Insert and update to FALSE.

Org.springframework.beans.factory.BeanCreationException:
Error creating Bean with Name ' sessionfactory ' defined in ServletContext resource [/web-inf/applicationcontext.xml]:
Initialization of Bean failed;nested exception is org.hibernate.PropertyNotFoundException:Could not find a getters for ID In class
Error reason: The ID in Hibernate's mapping file is uppercase, and the ID in Pojo class is lowercase
Workaround: Either convert the ID in the Pojo class to uppercase, or rename the ID in the hibernate mapping file to lowercase.

3.Hibernate connection to JDBC
Hibernate is a lightweight package for JDBC, including JDBC's connection to the database (with the Hibernate.property configuration file implementation of course, the forname that encapsulates the JDBC),
and query, delete and other code, all with the object-oriented thinking with the code, hibernate through the HBM configuration file to the Po class fields and database related fields such as the database ID,
In the PO class is the Pravite Long ID; Public long getId ();p ublic setId (long id);
Then the HQL statement is also object-oriented, its query statement is not query database but query class, these implementations of the magic is an XML file, in fact, hibernate= encapsulated Jdbc+xml file

4.Hibernate contact with Spring
Some of the objects in Hibernate can be managed for spring, allowing the spring container to create some object instantiation in Hibernate. For example: Sessionfactory,hibernatetemplate and so on.
Hibernate is originally a database of some operations, placed in the DAO layer, and spring to the business layer method defines the transaction, the business layer calls the DAO layer method, very good to add hibernate operations to the transaction.

What is the paging mechanism with 5.Hibernate? If you don't use Hibernate's own paging, how do you page them?
1. Hibernate comes with paging mechanism: After the session object is obtained, the query object is obtained from the session. With Query.setfirstresult (): Sets the first row of data to be displayed,
Query.setmaxresults (): Sets the last row of data to display.
2, do not use hibernate comes with the page, you can use the SQL statement paging,
For example: 5: Records displayed for each page, 2 is the current page: SELECT * Top 5 from table where tabId not in (select TabId Top (2-1) is from table);

Three persistence states for 6.hibernate objects and explanations?
The three persistent states of Hibernate objects are not known, only three states of Hibernate objects are known, as described below.

What is returned in a one-to-many configuration file in 7.hibernate?
A one-to-many configuration file in Hibernate is mapped to two tables, and the relationship between them is one-to-many.
For example: a relationship between a student and a classes table. A student can only be one class, and one class may have more than one student.

What is the difference between 8.update () and Saveorupdate ()?
Update () and saveorupdate () are used for state management of the PO that crosses the session.
The object that the update () method operates on must be a persisted object. That is, the update () method cannot be used if the object does not exist in the database.
The Saveorupdate () method operates on objects that can either be persisted or made non-persisted. If the persisted object calls Saveorupdate (), it will
Updates the objects in the database, or save to the database if the object is not persisted by using this method.

How to convert between three states of 9.hibernate
When an object is a save () by an instantaneous state (Transient), it becomes persisted.
When we store objects in the session, we actually save a copy of the session map,
That is, it puts a copy in its cache, and then it saves a copy in the database, which is called a persistent object (persistent) in the cache.
Session a close (), its cache is also closed, the entire session will be invalidated,
At this point, the object becomes a Free State (Detached), but it still exists in the database.
When the Free State (Detached) is update (), it becomes a persistent state (persistent).
When the persistent state (persistent) Delete () becomes transient (Transient),
At this point, there are no records in the database that correspond to it.

10.hibernate Why is the connection denied and the server crashed? Minimum of 5 Write
1. DB Not open
2. There may be a problem with the network connection
3. The connection configuration is wrong.
4. Is the driver's driver,url all right?
5. Lib to add the appropriate driver, the data connection code is wrong
6. There may be a problem with the database configuration
7. There are too many current joins and the server has a limited number of visitors.
8. The corresponding port of the server is not open, that is, it does not provide the corresponding service
9 What are the caches for hibernate, and how are they used separately?
10 What is your understanding of hibernate?
11 write a SQL statement that reflects a one-to-many relationship in Hibernate

11.Hibernate Introduction
Hibernate is an open-source object-relational mapping framework that provides JDBC with a very lightweight object encapsulation that allows Java programmers to manipulate databases at will using object programming thinking. Hibernate can be applied to any JDBC application, both in Java client applications and in servlet/jsp Web applications, and most revolutionary of all, hibernate can replace CMP in the EE architecture of the EJB application. The task of achieving data persistence.
Hibernate has a total of 5 core interfaces: Session, sessionfactory, Transaction, query, and configuration. These 5 core interfaces will be used in any development. Through these interfaces, you can not only access persistent objects, but also enable transaction control. These five core interfaces are described separately below.
? Session Interface: The session interface is responsible for performing crud operations on persisted objects (the task of crud is to complete the communication with the database, including many common SQL statements. )。 However, it is important to note that the session object is non-thread-safe. At the same time, Hibernate's session differs from the HttpSession in JSP applications. When the term "session" is used, it is actually referring to the session in Hibernate, and later the Httpsesion object is called the user session.
? Sessionfactory interface: The Sessionfactroy interface is responsible for initializing hibernate. It acts as a proxy for the data storage source and is responsible for creating session objects. The factory model is used here. It is important to note that Sessionfactory is not lightweight, because in general, a project typically requires only one sessionfactory, and when you need to manipulate multiple databases, you can specify a sessionfactory for each database.
? Config interface: The configuration interface is responsible for configuring and starting Hibernate, creating Sessionfactory objects. During Hibernate startup, the instance of the configuration class first locates the map document location, reads the configuration, and then creates the Sessionfactory object.
? Transaction interface: The transaction interface is responsible for transaction-related operations. It is optional, and developers can also design their own underlying transaction-processing code.
? Query and Criteria interface: query and Criteria interfaces are responsible for executing various database queries. It can be expressed in either the HQL language or the SQL statement.
12.Hibernate PRIMARY Key Introduction
Assigned
The assigned method generates a primary key value by the program and will throw an exception if it is specified before save ()
Feature: The generated value of the primary key is determined entirely by the user, regardless of the underlying database. The user needs to maintain the primary key value and specify the primary key value before calling Session.save ().
Hilo
Hilo uses a high-low algorithm to generate a primary key, and the low-level algorithm uses a high value and a low value, and then stitching together the two values of the algorithm as the unique primary key in the database. The Hilo approach requires additional database tables and fields to provide high-level value sources. By default, the table used is
Hibernate_unique_key, the default field is called Next_hi. Next_hi must have a record otherwise an error will occur.
Features: Additional database table support is required to guarantee the uniqueness of the primary key in the same database, but it does not guarantee the uniqueness of the primary key between multiple databases. The Hilo primary key generation method is maintained by hibernate, so Hilo is not independent of the underlying database, but should not manually modify the values of the tables used by the Hi/lo algorithm, or it will cause duplicate exceptions for the primary key.
Increment
The increment method generates a new primary key value in a way that automatically increases the primary key value, but requires support from the underlying database sequence. such as ORACLE,DB2 and so on. You need to include the settings for the increment flag in the map file xxx.hbm.xml.
Features: Maintained by hibernate itself, suitable for all databases, not suitable for multi-process concurrent update database, suitable for a single process to access the database. cannot be used in a clustered environment.
Identity
Identity was based on the underlying database to support autogrow, and different databases used different primary key growth modes.
Features: Related to the underlying database, requires the database to support identity, such as MySQL is auto_increment, SQL Server is identity, the supported databases are MySQL, SQL Server, DB2, Sybase and Hypersonicsql. The identity does not require hibernate and user intervention, it is easier to use, but it is not easy to migrate programs between different databases.
Sequence
Sequence requires the underlying database to support sequence methods, such as Oracle database, etc.
Features: The support sequence of the underlying database is required, the database that supports the sequence has DB2, POSTGRESQL, Qracle, sapdb, and so on, porting the program between different databases, especially from the database that supports the sequence to the database that does not support the sequence needs to modify the configuration file
Native
The native primary key generation method automatically selects the identity, Sequence, and Hilo primary key generation methods based on different underlying databases
Features: Depending on the underlying database, different primary key generation methods are used. Because Hibernate uses different mapping methods based on the underlying database, it is easy to migrate programs, which can be used if multiple databases are used in a project.
Uuid
The UUID uses the 128-bit UUID algorithm to generate the primary key, which can guarantee the uniqueness of the primary key under the network environment, and can guarantee the uniqueness of the primary key under different database and different server.
It can guarantee the uniqueness of the primary key in the database, and the generated primary key occupies more storage space.
Foreign GUID
Foreign is used in a one-to-one relationship. The GUID primary key generation method uses a special algorithm that guarantees the uniqueness of the generated primary key and supports SQL Server and MySQL
A brief introduction to the role of several packages in 13.Hibernate source code
Net.sf.hibernate.* the class of the package is basically the interface class and the exception class
Implementation class of Net.sf.hibernate.cache.* JCS
net.sf.hibernate.cfg.* configuration file Read class
Net.sf.hibernate.collection.* Hibernate Collection Interface implementation classes, such as list,set,bag and so on, Hibernate has to write its own collection interface implementation class to support the lazy loading
net.sf.hibernate.connection.* provider of several database connection pools
Net.sf.hibernate.dialect.* supports a variety of database features, each dialect implementation class represents a database that describes the data types and other features that the database supports, such as whether there are autoincrement, sequence, Do you have paged SQL and so on?
Examples of net.sf.hibernate.eg.* hibernate documentation
Net.sf.hibernate.engine.* the class function of this package is relatively scattered
Net.sf.hibernate.expression.* HQL Supported expressions
Net.sf.hibernate.hq.* HQL Implementation
net.sf.hibernate.id.* ID Generator
Net.sf.hibernate.impl.* Most core package, some important interface implementation class, if Session,sessionfactory,query etc.
Net.sf.hibernate.jca.* JCA Support, the session is packaged as a JCA-enabled interface implementation class
net.sf.hibernate.jmx.* I do not know jmx, only know that JMX is used to write app server hypervisor, presumably the implementation of the JMX part of the interface, so that app server can manage hibernate through the JMX interface
Net.sf.hibernate.loader.* is also a very central package, mainly the generation of SQL statements
net.sf.hibernate.lob.* Blob and CLOB support
net.sf.hibernate.mapping.* Properties for HBM files
Meta implementation of Net.sf.hibernate.metadata.* PO
Net.sf.hibernate.odmg.* ODMG is an ORM standard, this package is ODMG standard implementation class
Net.sf.hibernate.persister.* core package for mapping between persistent objects and tables
Net.sf.hibernate.proxy.* Proxy and lazy loading support
Net.sf.hibernate.ps.* The package is preparedstatment Cache
net.sf.hibernate.sql.* Generating a JDBC SQL statement package
Net.sf.hibernate.test.* test class, you can use JUnit to test hibernate
Net.sf.hibernate.tool.hbm2ddl.* generating DDL with HBM configuration files
net.sf.hibernate.transaction.* Hibernate Transaction Implementation class
Net.sf.hibernate.type.* hibernate defines the data type of the persisted object's properties
Net.sf.hibernate.util.* some tools, the role of a more scattered
net.sf.hibernate.xml.* XML Data Binding
14. Cache Management
Hibernate provides a level two cache, and the first level of cache is session-level caching, which is a transaction-scoped cache. This level of caching is managed by Hibernate, and generally does not require intervention; the second level of caching is the cache at the sessionfactory level, which is a process-wide or cluster-wide cache. This level of caching can be configured and changed, and can be dynamically loaded and unloaded. Hibernate also provides a query cache for query results, which relies on a second-level cache.
  1. Primary cache and level two cache comparison: first level cache second level cache holds data in the form of a range of transactional scopes of the bulk data cache of the persisted object object, each transaction has a separate first level cache process scope or cluster scope, and the cache is shared by all transactions within the same process or cluster for concurrent access policies Because each transaction has a separate first-level cache, there is no concurrency problem and there is no need to provide a concurrent access policy because multiple transactions concurrently access the same data in the second-level cache, the appropriate concurrency access policy must be provided to ensure that a specific transaction isolation level data expiration policy does not provide a data expiration policy. Objects in the first-level cache never expire unless the application explicitly empties the cache or clears a specific object must provide a data expiration policy, such as the maximum number of objects in the memory-based cache, the longest time allowed for the object to be in the cache, and the maximum idle time allowed for the object to be in the cache Physical storage media memory memory and hard disk. The bulk data of an object is first stored in an intrinsic cache, and when the number of objects in memory reaches the limit specified in the data expiration policy, the remaining objects are written to the hard disk-based cache. Cached software implementations include the implementation of the cache in hibernate session provided by a third party, hibernate only provides a cache adapter (Cacheprovider). Used to integrate specific cache plugins into hibernate. How caching is enabled as long as the application performs the operations of saving, updating, deleting, loading, and querying database data through the session interface, Hibernate enables the first level cache, copies the data in the database to the cache as objects, and for bulk updates and bulk deletions, If you do not want to enable the first level of caching, you can bypass the Hibernate API and execute the instructions directly through the JDBC API. Users can configure a second-level cache on the granularity of a single collection of classes or classes. If an instance of a class is read frequently but is seldom modified, consider using a second-level cache. Only a second-level cache is configured for a class or collection, and hibernate joins its instance to the second-level cache at run time. How the user manages the cache the first-level cache of physical media is memory, and due to limited memory capacity, the number of loaded objects must be limited by appropriate retrieval policies and retrieval methods. The Evit () method of the session can explicitly empty the cache for specific objects, but this method is not recommended. The second-level cache of physical media can be memory and hard disks, so the second-level cache can hold a large amount of data, and the Maxelementsinmemory property value of the data expiration policy can control the number of objects in memory. Managing a second-level cache consists of two main areas: Select the persistence class that needs to use the second level cache, set the appropriate concurrency access policy: Select the cache adapter, set theThe appropriate data expiration policy.
2. First-level cache management: When the application calls save (), update (), Savaeorupdate (), get () or load () of the session, and the list (), iterate (), or filter () method that invokes the query interface, If the corresponding object does not exist in the session cache, hibernate will add the object to the first level cache. When you clean up the cache, hibernate synchronizes updates to the database based on the state of the objects in the cache. Session provides two ways for the application to manage the cache: evict (object obj): Clears the persisted object specified by the parameter from the cache. Clear (): Empties all persisted objects in the cache.
3. Management of Level two cache:
The general process for 3.1. Hibernate's level two cache strategy is as follows:
1) When a condition is queried, always issue a SELECT * FROM table_name where .... (select all fields) such SQL statements query the database and get all the data objects at once.
2) Put all the obtained data objects into the second level cache based on the ID.
3) When hibernate accesses the data object according to the ID, it is first checked from the session cache, and if the level two cache is configured, it is checked from the level two cache, and the database is not found, and the result is placed in the cache by ID.
4) Update the cache while deleting, updating, and adding data.
Hibernate's level two cache policy, which is a cache policy for ID queries, has no effect on conditional queries. To do this, Hibernate provides query Cache for conditional queries.
3.2. What kind of data is suitable for storage in the second level cache? 1 rarely modified data 2 is not very important data, allowing the occasional concurrent data 3 will not be accessed concurrently data 4 reference data, refers to the supply of constant data reference, its limited number of instances, its instances will be referenced by many other instances of the class, the instance is rarely or never modified.
3.3. Not suitable for storing data in a second level cache? 1 frequently modified data 2 financial data, which is absolutely not allowed to occur concurrently with 3 of data shared with other applications.
3.4. Common Cache Plugin Hibernater's level two cache is a plug-in, and here are a few common cache plugins:
EhCache: As a process-wide cache, the physical media that holds the data can be either memory or hard disk, which provides support for Hibernate's query caching.
Oscache: As a process-wide cache, the physical media that holds the data can be either memory or hard disk, providing a rich cache data expiration policy that supports Hibernate's query caching.
Swarmcache: Can be used as a cluster-wide cache but does not support Hibernate's query cache.
JBossCache: Can be used as a cluster-wide cache, supports transactional concurrency access policies, and provides support for hibernate query caching.
3.5. The main steps for configuring level two caching:
1) Select the persistence class that requires a level two cache, and set its concurrent access policy for the named cache. This is the most serious step to consider.
2) Select the appropriate cache plug-in, and then edit the plugin's configuration file.

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

Hibernate face Test

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.