Hibernate level two cache and HQL (iii)

Source: Internet
Author: User

Hibernate Retrieval Method
1:hibernate provides the following ways to retrieve objects 1, the navigation object graph retrieval Method: Obtains the persistent entity object in the program, through the object Association, obtains the related entity object. For example: Session.get (department.class,1); Dept.getemps () 2, OID retrieval method: The session of Get or load based on the OID to find object 3, hql retrieval mode: query interface. Query by using object-oriented HQL statements 4, QBC (query by Criteria) Retrieval method: the criteria interface. Provides a more object-oriented query interface. 5, local SQL retrieval method: SQLQuery. High performance requirements. Hibernate is responsible for mapping the retrieved JDBC resultset result set to a persisted object graph. Generally do not need 2.  Hibernate link query type within connection inner JOIN or join urgently inside join INNER JOIN fetch or join FETCH implicit INNER join left outer link ieft outer JOIN or left JOIN urgent zuo outer link ieft Outer JOIN fetch or LEFT JOIN fetch returns data different right outer join outer JOIN or starboard join Cross link classa,classb** differentiate between left join and the difference of the urgent link 3. HQL Query Special Usage 1). The polymorphic query queries out all entities (instances of the current class and all subclasses) Session.createquery ("from Customer") retrieves all instances that implement the Serializable interface Session.createquery ("from Java.io.Serializable ") Retrieves all persisted object query query = Session.createquery (" from Java.lang.Object ") 2). Paged query: setfirstresult (int firstresult): Sets the object from which to start the retrieval, the parameter Firstresult represents the index position of the object in the query results, and the starting value of the index position is 0. By default, query starts from the first object in the query results. Setmaxresult (int maxResults): Sets the maximum number of objects retrieved at one time. By default, the query and Criteria interfaces retrieve all of the object 3 in the results.Single result set query.setmaxresults (1);//Long returns several records Customer C = (customer) query.uniqueresult ();//returns 0 to 1 data 4). Parameter binding Method 1: Specify the name parameter binding, using Setstring/setinteger/query.setparameter (0, "Tom") mode 2: Specify the parameter's position binding, query.setstring (0, "Tom")/ Query.setparameter (0, "Tom"); 5). Specify the query statement in the configuration file <query name= "Findcustomersbyname" > <! [Cdata[from Customer C where c.name like?]] ></query>------------------------------------------------------------------Query Query = Session.getnamedquery ("Findcustomersbyname"); 6). The SQL statement that is used by the urgent left outer join is still a left outer join, and it returns an object that needs to traverse the loop in order to get the object associated with it. Cons: Too many loops, the result set returned is too complex 7). Left OUTER JOIN if you query an object, it returns the object array object 8 If you are querying multiple objects. The projection query results contain only part of the attributes of the entity. Implemented by the SELECT keyword. Returns an object array or an object 9). The constructor queries the new Com.baidu.CustomerRow (C.name,o.ordernumber,o.price) from Customer4. Local SQL query Way one: Query query = Session.createsqlquery ("Select O.name from CUSTOMERS C where c.name= ' Tom '"); Query.list (); Mode two: parameter query queries query = Session.createsqlquery ("SELECT * from CUSTOMERS C where c.name=?"); Query.setstring ("0", ' Tom ') Query.list (); Return object at this timeThe array either returns an object (here if the query result is 1 values, which is the object object, if the query result is multiple values is an object array three: The SQL statement encapsulates the object sqlquery sqlquery = Session.createsqlquery ("Select {c.*} from CUSTOMERS C where c.name =:customername");//Dynamic binding parameter Sqlquery.setstring ("  CustomerName "," Tom ");//" C "is used to refer to the alias of the data table, for example, {c.*} in the above code means using C as the Customers table alias. The relational data returned by the SQL query is mapped to the object sqlquery.addentity ("C", customer.class);//executes the SQL SELECT statement and returns the result of the query. List List = Sqlquery.list (); 5. QBC queries are made up of criteria, criterion interfaces, and expression classes, and he supports dynamically generating query statement method chain programming at run Time: Session.createcriteria (Customer.class). Add ( Restrictions.eq ("name", "Tom1")). List ();

Second-level cache
1. Two-level cache meaning memory stores frequently-manipulated data, reduces interaction with the database, and improves performance by 2. The role of the second-level cache 1). Because level two caches are public caches and are process-level caches, level two caches hold public data, and private data cannot be stored here for 2. When a data is put into a level two cache, the data in the level two cache can exist as long as the sessionfactory is not closed (3). Hibernate itself does not implement 3 for level two caches. Configure level two cache 1), in Hibernate configuration file//Open Level two cache <property name= "Cache.use_second_level_cache" >true</property>// Specify the vendor for level two cache <property name= "Cache.provider_class" >org.hibernate.cache.ehcacheprovider</property>// Turn on statistical mechanism <property name= "Hibernate.generate_statistics" >true</property>2), specify class or set to turn on level two cache, There are two scenarios in Hibernate configuration file//Open class level two cache <class-cache usage= "read-only" class= "cn.itheima03.hibernate.domain.Classes" />//open Set Level two cache//description: The condition of opening the collection's level two cache must be student Class two cache also open <collection-cache usage= "read-only" collection= "Students" /> in the mapping File//Open class level two cache <class name= "cn.itheima03.hibernate.domain.Classes" table= "Classes" ><cache usage= " Read-write "/>//open the collection's level two cache <set name=" students "><cache usage=" Read-only "/>4. The memory structure of the secondary cache level two cache is provided by the cache provider (cache Provider), which contains four parts: Class buffers, collection buffers, query buffers, update timestamps <!--configuration classesLevels of Level two cache--><class-cache usage= "Read-write" class= "com.itheima.domain.Department"/><class-cache usage= " Read-write "class=" Com.itheima.domain.Employee "/><!--Configuring a Level two cache--><collection-cache usage= at the collection level" Read-write "collection=" Com.itheima.domain.Department.emps "/>1). The first time the class buffer is queried, the data is stored in the primary cache and the level two cache, but the storage form is different. The first-level cache holds a reference to the entity object (that is, the memory address), and the level two cache holds the data in the object (hashed data id:1 name:d1name) * * * NOTE: The first-level cache is not closed, the same entity record is queried again, and the object's reference is returned. Therefore, the memory address of the objects removed from the first cache is consistent two times. When the first-level cache is closed, the data extracted from the level two cache is hashed and needs to be repackaged into the new object, so the memory address will be different get and load can read class level two cache, query.list can only be saved, cannot be fetched, list will query 2 again). The collection-level cache of level two * holds the OID of the object and, if you want to get a real entity object, is summarized in level two cache at the class level: the cache at the collection level depends on the class-level cache 3). Query buffer A. For frequently used query statements, if query caching is enabled, Hibernate will store the query results in the query cache when the query is executed for the first time. When you execute the query statement again later, you only need to get the query results from the cache, thus improving query performance B. Query caching is used when the application runs frequently using query statements to insert, delete, and update operations on data that are retrieved from a query statement infrequently. The HQL from department data is stored in the class buffer, the ID of the query buffer store object if the query cache is configured: The SQL statement will be key, the query result is the value of D. Configuration steps: Start the query cache hibernate.cfg.xml:<property name= "Hibernate.cache.use_query_cache" >true</property> Used in the program: QUERY.SETCACHEABLE (True); 4). Update timestamp update timestamp level cache area * (1) Place the object of the query in a class, collection, level two cache of the query, and set the time to drop the object T1 * (2) when the increment, delete, change operation, the update timestamp will record a time T2 if t1>t2, After the query is updated, it indicates that the data stored in the level two cache is up-to-date, then the data is fetched from the level two cache and database 5 is not queried. What data is stored in the cache? data that fits into a level two cache: infrequently modified data is not very important, allowing occasional concurrency problems that are not suitable for placing data in a level two cache: frequently modified financial data, never allow concurrency problems to share with other application data
Transaction processing
1. Handling concurrency regardless of transaction isolation level problems: dirty read, non-repeatable read, wasted; (research missing updates) missing updates: Two threads with different transactions concurrently manipulate one piece of data, after which the committed transaction overwrites the data that commits the transaction to resolve the lost Update method: Pessimistic Lock: Think that the lost update must occur. Use the lock mechanism of the database (generally with exclusive lock). That is, lock shared locks (read) on data when querying data: A table can add multiple read locks. SELECT * from XXX lock in share mode; Read more locks, neither side can write. Exclusive Lock (Write): A table can only add one lock, with any lock exclusion. SELECT * from XXX update; Any change to the statement will automatically add an exclusive lock optimistic lock: Assume that the missing update will not occur. Locks that do not depend on the underlying database. Add a version field of 2 to the entity. Set the transaction isolation level in Hibernate configuration file dirty read, non-repeatable read, virtual read prevent 1READ Uncommitted2read by setting isolation level Committed4repeatable-read 8SERIALIZABLE set by configuration parameter hibernate.connection.isolation=1|2|4|8 Note: MySQL default is 4;oracle default is 23. Maintain database connection pool with external data source: Configure C3P01). Add the C3P0 jar package to build path 2). Hibernate.cfg.xml Add the following configuration (ref.: etc/hibernate.properties) <property name= "Hibernate.connection.provider_class" > Org.hibernate.connection.c3p0connectionprovider</property>

Hibernate level two cache and HQL (iii)

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.