The third part: Basic Development of Hibernate

Source: Internet
Author: User

1: Transient-objects created by the new operator and not associated with the Hibernate Session are considered instantaneous. The instantaneous object will not be persisted into the database, nor will it be assigned a persistent identifier (identifier ). If the instantaneous object is not referenced in the program, it will be destroyed by the garbage collector. Hibernate Session can be used to change it to a persistent state, and Hibernate will automatically execute necessary SQL statements.
 
2: Persistent-a Persistent instance has a corresponding record in the database and has a Persistent identifier. A persistent instance may be saved or loaded. Either type exists within the scope of the associated Session by definition. Hibernate detects any changes to objects in the persistent state and synchronizes the object data with the database when the current operation unit is completed. Developers do not need to manually execute UPDATE. You do not need to manually execute the DELETE statement to change an object from a persistent state to an instantaneous state.
 
3: Detached-after the Session associated with the persistent object is closed, the object becomes denied. The reference to the unmanaged object is still valid, and the object can be modified. If the unmanaged object is re-associated to a new Session, it will be converted to persistent, and the changes made during the unmanaged process will be persisted to the database.
 
PassSessionInterface to operateHibernate
New-- SaveMethod,PersistMethod
1: persist () makes a temporary instance persistent. However, it does not guarantee that the Identifier value is immediately assigned to the persistent instance, which will occur during the flush process. Persist () also ensures that it does not execute the INSERT statement when the transaction boundary is called out. This is useful for long-running sessions with extended sessions/persistent context.
2: save () ensures that an identifier is returned. If you need to run INSERT to obtain the identifier (such as "identity" rather than "sequence" generator), this INSERT will be executed immediately, whether inside or outside the transaction. This may cause problems for long-running sessions with extended sessions/persistent context.
 
Delete-- DeleteMethod
Modify--There are four ways to do this:
1: directly load the object when the Session is opened, and then modify the Persistent Object. when the transaction is committed, the object is automatically flushed to the database.
2: Modify managed objects. update or merge methods are available.
3: Automatic status detection: saveOrUpdate Method
UpdateAndMergeMethod
1: If the record you want to modify exists in the Database, update directly executes the modification statement each time. merge first searches for the record in the cache and no data exists in the cache, go to the database to query and then merge the data. If the data is the same, the merge method will not modify the data. If the data is different, merge will actually modify the database.
2: If the record you want to modify does not exist in the Database, update reports an error, while the merge method adds a new value to the database.
3: After update, the incoming TO object is PO, and merge is still.
4: If you are sure that the current session does not contain a persistent instance with the same persistent ID, use update (). If you want to merge changes at any time without considering the session status, use merge (). In other words, in a new session, the first update () method is usually called to ensure that the operations on the re-join and unmanaged objects are first executed.
5: Note: If you use update TO change a to po, you must execute the update SQL statement no matter whether the object is modified or not.
 
 
 
 

Generally, update () or saveOrUpdate () is used in the following scenarios ()
1: The program loads objects in the first session.
2: The object is passed to the presentation layer.
3: Some changes have been made to the object.
4: The object is returned to the business logic layer.
5: The program calls the update () method of the second session to persist these changes.
 
The saveOrUpdate method does the following:
1: If the object has been persisted in this session, do not do anything
2: if another object associated with this session has the same persistent identifier, an exception is thrown.
3: if the object does not have a persistent identity attribute, call save ()
4: If the persistent identifier of an object indicates that it is a new instantiated object, save () is called for it ().
5: if the object is with version information (via <version> or <timestamp>) and the value of the version attribute indicates that it is a new instantiated object, save () It.
6: otherwise, the update () object
 
Merge does the following:
1: If the session contains instances with the same persistence identifier, use the object state provided by the user to overwrite the old persistent instance.
2: If the session does not have a persistent instance, try to load it from the database or create a new persistent instance.
3: the persistent instance is returned.
4: The object given by the user is not associated with the session, and it is still out of management.
 
Query by primary key
1: load Method: when load is used, first query the level-1 cache. If no value is found, a proxy object is created and returned. When used, the level-2 cache is queried, if there is no data in the second-level cache, query the database. If there is no data in the database, leave the exception
2: get method: first check the cache. If no specific data exists in the cache, query the database. If no value exists in the Database, null is returned. In short, the get method is not used, get real data
Hibernate supports conditional Query
1: The most important way to Query by condition is to use the Query interface and HQL
2: local Query (native SQL): standard SQL is used. It is also implemented through the Query interface.
3: Query By Criteria (QBC): Use a dynamic, object-oriented method to create a Query.
4: Query By Example (QBE): similar to our own getByCondition
5. name Query: configure the hql statement in hbm. xml and create the Query interface by name in the program.
List Method of Query
A query is usually executed when list () is called. The execution result is fully loaded into a set in the memory, and the objects returned by the query are in a persistent state. If you know that the query returns only one object, you can use the list () shortcut uniqueResult ().
Iterator and List
In some cases, you can use the iterate () method to achieve better performance. This is usually because the expected results already exist in the session or second-level cache. Otherwise, iterate () will be slower than list (), and may require multiple database access for simple queries: iterate () first, we use one statement to obtain the identifiers of all objects, and then execute n additional select statements to instantiate the actual objects.
 
External name query
You can define the name query (named queries) in the ing file ).

Java code:
1. <query name = "s">
2. <! [CDATA [select Object (o) from UserModel o]>
3. </query>
Parameter binding and execution are completed programmatically:
List list = s. getNamedQuery ("cn. s. h3.hello. UserModel. javass"). list ();
Note that you must use a fully qualified name and name for access.
 
Flush Method
During each interval, the Session will execute some necessary SQL statements to synchronize the status of objects in the memory to the JDBC connection. This process is called flush. It will be executed at the following time points by default:
1: before some queries are executed
2: When org. hibernate. Transaction. commit () is called
3: When Session. flush () is called
The SQL statements involved are executed in the following order:
1. All statements for inserting objects are executed in the chronological order of save ().
2. All statements for updating objects
3. All statements for deleting a set
4. All statements for deleting, updating, or inserting collection Elements
5. All statements for set insertion
6. All statements for deleting objects are executed in the chronological order of delete ().
Unless you explicitly issue the flush () command, it is completely uncertain about when the Session will execute these JDBC calls. They can only ensure the execution order. Of course, Hibernate guarantees that Query. list (...) will never return invalid data or error data.
Lock method: it also allows the program to re-associate an object to a new session. However, the unmanaged object must have not been modified. Example: s. lock (um, LockMode. READ );
Note: lock is mainly used for transaction processing, and the associated object is only an attached function.
 
Get metadata
Hibernate provides the ClassMetadata interface and Type to access metadata. Example:

Java code:
View copies to clipboard and print
1. ClassMetadata catMeta = sf. getClassMetadata (UserModel. class );
2. String [] propertyNames = catMeta. getPropertyNames ();
3. Type [] propertyTypes = catMeta. getPropertyTypes ();
4. for (int I = 0; I <propertyNames. length; I ++ ){
5. System. out. println ("name =" + propertyNames [I] + ", type ="
6. + propertyTypes [I]);
7 .}
8.
HQL Introduction
Hibernate is equipped with a very powerful Query Language, which looks like SQL. But no
To be confused by syntax-structure similarity, HQL is designed to be fully Object-oriented for queries.
It can understand concepts such as inheritance, polymorphism, and association.
Let's look at an example to see If SQL and HQL are the same and different:
SQL: select * from tbl_user where uuid = '000000'
HQL: select Object (o) from UserModel o where o. uuid = '000000'
HQL features
1: HQL is case sensitive to Java classes and attributes and is not case sensitive to others.
2: basically, SQL and HQL can be converted, because according to the implementation principle of Hibernate, the final run is SQL, but it is automatically generated.
3: HQL supports internal and external connections
4: HQL supports clustering functions, such as count, avg, sum, min, and max.
5: HQL supports order by and group
6: HQL supports conditional expressions, such as in, like, and.
Select clause
1: directly return the object set, for example, select o from UserModel o
2: returns a set of specific types, such as select o. name from UserModel o.
3: return Object [], for example, select o. uuid, o. name from UserModel o
4: return List, for example, select new List (o. uuid, o. name) from UserModel o
5: return any object, for example, select new cn. javass. h3.hello. A (o. uuid, o. name) from UserModel o, which requires A constructor for object A to input these two parameters.
6: The returned Map type, for example, select new Map (o. uuid as Id, o. name as N) from UserModel o, the returned result is the map key using the alias after as, and the corresponding data is used as the value.
 
From clause
1: direct from object, such as: from UserModel
2: aliases can be allocated, for example, from UserModel as um. The as keyword can be omitted.
3: if there are multiple objects following from, for example, from UserModel and DepModel, it is equivalent to multi-table joint query and Their Cartesian product is returned.
 
Aggregate functions
1: supported avg, sum, min, max, count
2: The keywords distinct and all can also be used. They have the same semantics as SQL, for example:
Select count (distinct o. name) from UserModel o
Nwhere clause
1: If no alias is specified, use the attribute name directly.
2: If an alias is assigned, you must use the alias. Attribute method.
3: The expressions allowed in the where clause include most expressions used in SQL, including:
(1) mathematical operators + ,-,*,/
(2) binary comparison operator =, >=, <=, <> ,! =, Like
(3) logical operators and, or, not
(4) parentheses (), indicating grouping
(5) in, not in, between, is null, is not null, is empty, is not empty, member of and not member
(6) string connector... |... or concat (...,...)
(7) current_date (), current_time (), and current_timestamp ()
(8) second (...), minute (...), hour (...), day (...), month (...) and year (...)
(9) EJB-QL 3.0 defines any function or operator: substring (), trim (), lower (), upper (), length (), locate (), abs (), sqrt (), bit_length (), mod ()
(10) coalesce () and nullif ()
(11) str () converts a number or time value to a readable string
(12) cast (... as ...), the second parameter is the name of a Hibernate type and extract (... from ...), as long as ANSI cast () and extract () are supported by the underlying database
(13) The HQL index () function acts on the alias of the sorted set of join.
(14) The HQL function uses the set as the parameter: size (), minelement (), maxelement (), minindex (), maxindex (), and special elements () and indices functions can be limited with quantifiers: some, all, exists, any, in.
(15) SQL scalar functions supported by any database, such as sign (), trunc (), rtrim (), sin ()
(16) How does one pass in JDBC-style parameters?
(17) name parameter: name,: start_date,: x1
(18) SQL direct constants 'foo', 69, 6.66E + 2, '2017-01-01 10:00:01. 0'
(19) Java public static final type constant eg. Color. TABBY
Group by clause
1: Query of returned aggregate values can be grouped by any attribute.
2: The having clause can be used.
3: Clustering functions in SQL can appear in the having clause.
4: The group by clause and order by clause cannot contain arithmetic expressions.
5: you cannot group by an object. You must explicitly list all clustering attributes.
 
Order by clause
The list returned by a query can be sorted by any attribute in a returned class or component. The optional asc or desc keyword indicates that the list is sorted in ascending or descending order.
 
Subquery
For databases that support subqueries, Hibernate supports using subqueries in queries. A subquery must be surrounded by parentheses.
N join)
1: Hibernate can use join between related entities. Similar to SQL, it supports inner join, left outer join, right outer join, and full join (full join, not commonly used ).
2: inner join can be abbreviated as join, while left outer join and right outer join can be abbreviated as outer.
With
With the with keyword of HQL, You can provide additional join conditions.
For example, from Cat as cat left join cat. kittens as kitten with kitten. bodyWeight> 10.0
Fetch
You can request to immediately return the associated set object, such:

Java code:
1. from Cat as cat
2. inner join fetch cat. mate
3. left join fetch cat. kittens
How can we use join for non-correlated entities?
If you want to use join for entities without association, you can use SQL for local queries. For example:
S. createSQLQuery ("select um. *, dm. * from tbl_user2 um left join tbl_dep dm on um. age = dm. uuid ")
. AddEntity ("um", UserModel. class). addEntity ("dm", DepModel. class );
1: New
2: load, get
3: Modify
4: query by conditions
(1) method for passing in the condition value :? Or: name. The index starts from 0.
(2) assign values to parameters
(3) returned object
(4) multiple attributes are returned to form an Object []
(5) Hibernate Implementation of getByCondition
5. Delete
6: Paging
Query q = sess. createQuery ("from DomesticCat ");
Q. setFirstResult (20 );
Q. setMaxResults (10 );
List cats = q. list ();
 
You can also use the Native SQL language of your database to query data. This is for
Some features (such as the query prompt or the CONNECT keyword in Oracle) are very
. This allows you to migrate the original SQL/JDBC-based program to a Hibernate-based application.
Obstacles on the road.
Use SQLQuery
Native SQL query execution is controlled through the SQLQuery interface, through execution
Session. createSQLQuery () to obtain this interface. The following describes how to use this API for queries.
Scalar queries)
S. createSQLQuery ("select uuid, name from tbl_user"). list ();
It returns a List composed of objects []. Hibernate uses ResultSetMetadata to determine the actual sequence and type of returned scalar values. You can also use scalar to specify the type, for example:
S. createSQLQuery ("select * from tbl_user"). addScalar ("id", LongType. INSTANCE)
The id field is of the long type. You can also specify the type of many fields.
Entity queries)
The above queries all return scalar values, that is, the "Raw" data returned from the resultset. The following shows how to use addEntity () to get the native query to return object objects.
(1) s. createSQLQuery ("select * from tbl_user"). addEntity (UserModel. class );
(2) s. createSQLQuery ("select uuid, userId from tbl_user2"). addEntity (UserModel. class); // You must list all the fields in the table.
(3) s. createSQLQuery ("select {um }. uuid as {um. uuid}, {um }. name as {um. name} from tbl_user {um }"). addEntity ("um", UserModel. class );
The function is similar to the second one. All fields in the table must be listed.
(4) Simple Syntax: s. createSQLQuery ("select * from tbl_user2 um ")
. AddEntity ("um", UserModel. class );
(5) Example of adding conditions:
S. createSQLQuery ("select * from tbl_user where uuid =? And name like? "). AddEntity (UserModel. class). setString (0," 3 "). setString (1," % na % ");
 
Named SQL query
You can define the query name in the ing document, and then directly call the named SQL query like calling a named HQL query. in this case, we do not need to call the addEntity () method.
Configure hbm. xml as follows:

Java code:
1. <SQL-query name = "users">
2. <return alias = "um" class = "cn. S. h3.hello. UserModel"/>
3. select um. name as {um. name },
4. um. age as {um. age },
5. um. uuid as {um. uuid}
6. from tbl_user um
7. where um. name like: name
8. </SQL-query>
Note: to return an object, you must list all the fields in the Table. Otherwise, the error "invalid column name" will be reported. In fact, when the reflection assigns a value to the object, this data is not returned from SQL.
Example of calling in the program: Query q = s. getNamedQuery (um. getClass (). getName ()
+ ". Users"). setString ("name", "% n % ");
 
Name SQL query -- use return-property
With <return-property>, you can clearly tell Hibernate which field aliases are used, replacing the {}-syntax for Hibernate to inject its own Alias.
Configure hbm. xml as follows:

Java code:
1. <SQL-query name = "users">
2. <return alias = "um" class = "cn. S. h3.hello. UserModel">
3. <return-property name = "name" column = "umName"> </return-property>
4. <return-property name = "uuid" column = "uuid"> </return-property>
5. <return-property name = "age" column = "age"> </return-property>
6. </return>
7. select um. name as umName,
8. um. age as age,
9. um. uuid as uuid
10. from tbl_user um
11. where um. name like: name
12. </SQL-query>
Hibernate features an intuitive and scalable conditional query API.
Create a Criteria instance
The org. hibernate. Criteria interface indicates a query of a specific persistent class. Session is the factory of the Criteria instance.

Java code:
View copies to clipboard and print
1. Criteria crit = sess. createCriteria (Cat. class );
2. crit. setMaxResults (50 );
3. List cats = crit. list ();
Restrict result set content
A separate query condition is an instance of the org. hibernate. criterion. Criterion interface org. hibernate. criterion. Restrictions class that defines the factory method for obtaining some built-in Criterion types.

Java code:
1. List list = s. createCriteria (UserModel. class)
2. add (Restrictions. eq ("uuid", "3 "))
3. add (Restrictions. like ("name", "% n % "))
4. list ();
5. constraints can be grouped by logic, for example:
6. List cats = sess. createCriteria (Cat. class)
7. add (Restrictions. like ("name", "Fritz % "))
8. add (Restrictions. or (
9. Restrictions. eq ("age", new Integer (0 )),
10. Restrictions. isNull ("age ")
11 .)
12.). list ();
Sort result sets
You can use org. hibernate. criterion. Order to sort the query results. Example:

Java code:
1. List cats = sess. createCriteria (Cat. class)
2. add (Restrictions. like ("name", "F % ")
3. addOrder (Order. asc ("name "))
4. addOrder (Order. desc ("age "))
5. setMaxResults (50)
6. list ();
1: If the following program exists, add 100000 pieces of data to the database:

Java code:
View copies to clipboard and print
1. Session session = sessionFactory. openSession ();
2. Transaction tx = session. beginTransaction ();
3. for (int I = 0; I <100000; I ++ ){
4. Customer customer = new Customer (.....);
5. session. save (customer );
6 .}
7. tx. commit ();
8. session. close ();
This program obviously cannot run normally and will throw an exception of memory overflow. According to the previous principles, the save method of Hibernate is to put data in the memory first, and there is too much data, resulting in memory overflow.
How can this problem be solved?
Solution:
1: first, set the parameter of the batch capture quantity of hibernate. jdbc. batch_size to an appropriate value (for example, between 10 and 50). At the same time, it is best to disable the second-level cache, if any.
2: Batch insert. a feasible solution is as follows:

Java code:
1. for (int I = 0; I <100000; I ++ ){
2. Customer customer = new Customer (.....);
3. session. save (customer );
4. if (I % 20 = 0 ){
5. // insert this batch of data into the database and release the memory
6. session. flush ();
7. session. clear ();
8 .}
9 .}
Batch update is similar to this method.
1: by default, Hibernate has a cache, which is called a level-1 cache.
2: You can also use StatelessSession to indicate that the level-1 cache is not implemented, and it does not interact with the level-2 Cache and query cache.
3: StatelessSession is a low-layer abstraction, which is very similar to the underlying JDBC.

Java code:
1. StatelessSession session = sessionFactory. openStatelessSession ();
2. Transaction tx = session. beginTransaction ();
3. ScrollableResults MERs = session. getNamedQuery ("GetCustomers"). scroll (ScrollMode. FORWARD_ONLY );
4. while (customers. next ()){
5. Customer customer = (Customer) MERs. get (0 );
6. customer. updateStuff (...);
7. session. update (customer );
8.} tx. commit (); session. close ();
9.

Author: jinnianshilongnian


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.