Hibernate learning Summary

Source: Internet
Author: User

Hibernate automatically creates a table:
In the configuration file: <property name = "hbm2ddl. Auto"> Create </property>
Create: Create at startup, do not delete the table at the end of the program, delete the table at next startup, and then create
Create-drop: Initialize the creation, and delete the table after the program runs.
Update: If the ing file and table structure are different, the table will be updated.
Validate: checks whether the table and the ing file correspond. If not, an error is returned.
By default, JDBC is automatically submitted.
Hibernian manually commits transactions by default. You must enable transactions and manually commit transactions. Otherwise, no records are saved in the database:
Eg:
Transaction Tx = getsession (). begintransaction ();
Getsession (). Save (transientinstance );
TX. Commit ();
This is for the InnoDB engine. InnoDB supports transactions and Foreign keys (rollback can be performed if no commit is performed after insertion)
If I have not submitted a transaction, but the MySQL database has data, this engine is MyISAM
The default MyISAM does not support transactions and Foreign keys (it does not matter whether the transaction is enabled or not, and cannot be rolled back after being inserted)
Transactions do not need to be opened during query.
Configuration File
<Property name = "show_ SQL"> true </property>: displays the SQL statement during execution.
Get (): Frequently Used
Load (): Use less
Load () will not access the database immediately, but will only access the database during the call, and the returned value will not be null,
Persist (): Save, not inserted when the transaction is not enabled
Save (): Save. if the transaction is not enabled, it will be inserted and then rolled back.
The status of the hibernate object:
Instantaneous: There is no matching record in the database. If it exceeds the scope, it will be reclaimed by the JVM garbage collector. Generally, it is new and corresponds to the session.
No associated object
Persistent: data in the database corresponds to the session. Currently, the session associated with the session is not closed, and the transaction is not initiated.
Transaction; the persistent object state changes, and the database is affected when the transaction is committed.
Unmanaged: the database has data corresponding to it, but no session is associated with it currently; the status of the managed object changes, Hibernate
Not Detected
Example: User user = new user (); // the user is instantaneous.
Session. Save (User); // associate the user with the session. The user is persistent.
Commit (); // all user updates are saved to the database.
Session. Close (); // the user will be disconnected from the session and will be disconnected from the session.
Update (): Process unmanaged objects
Saveorupdate (): you do not know the state of the object (obtain the status based on the ID), and save or update the object after calling it.
It becomes persistent. But after calling Merge (), the object is still out of control!
If the ID is of the int type, 0 indicates that no corresponding records exist in the database; if the ID is of the string type, null indicates that no
There is a corresponding record; if I want him to return another value, such as-1, you need to specify in the ing file: <ID name = ""
Unsaved-value = "-1">
When the user is persistent, if the object property changes, the object state is followed by the database by default when the object is submitted.
Synchronization can reduce interaction with the database and improve efficiency.
Query operation: hql and criteria
Hql:
The Object-Oriented Query Language. Unlike SQL, the objects in hql are case-sensitive (except for Java classes and attributes, the objects in hql are not highly case sensitive.
In lower case); hql queries objects rather than tables, and supports polymorphism. hql mainly uses query to create query:
Query q = session. createquery (hql );
. From persion
. From user where user. Name =: Name
. From user where user. Name =: Name and user. Birthday <: Birthday
Criteria
Criteria is a more Object-Oriented Query Method than hql; Criteria creation method:
Criteria crit = session. createcriteria (domainclass. Class );
Simple attribute conditions: criteria. Add (Restriction. eq (propertyname. Value )),
Criteria. Add (restrictions. eqproperty (propertyname. otherpropertyname ))
Example:
Hql:
Find a user based on the user name:
String hql = "from user (Class Name) as user where user. Name =? ";
Query q = session. createquery (hql );
Q. setstring (0, name );
List <user> List = Q. List (); // executequery () is similar
// User = (User) Q. uniqueresult (); // use this function if only one result is returned.
For (User: List ){
System. Out. println (user. getname ());
}
In the above example? If there are too many maps, the corresponding ones may not be as follows:
String hql = "from user as user where user. Name =: Name ";
Q. setstring ("name", name );
// Implement Paging
Q. setfirstresult (0 );
Q. setmaxresult (10); // obtain 10 records
Criteria:
Criteria c = S. createcriteria (user. Class );
// Constraints
C. Add (restrictions. eq (equal to) ("name", name); // The attribute name value is name
C. Add (restrictions. QT (greater than) ("Birthday", new date ()))
Or (OR)
LT (less)
// Pagination
C. setfirstresult (0 );
C. setmaxresult (10 );
List <user> List = C. List ();
// User u = (User) C. uniqueresult (); one-to-one relationship:
For example: person and idcard tables
The primary key ID of the person table increases by itself. The primary key ID of the id_card table does not need to increase by itself. It is the same as the ID in the person table, that is, the primary key.
Is also a foreign key
You can design the table as follows:
Create Table id_card (
Id int (11) not null,
...
...
Primary Key (ID)
Foreign key ('id') References 'person '('id') on Delete cascade on update cascade,
)
The person class has a private idcard (primary object );
The idcard class has a private person (slave object );
Ing file:
Idcard. HBM. xml:
<ID name = "ID">
<Generator class = "foreign">
<Param name = "property"> person </param>
</Generator>
</ID>
<One-to-one name = "person" constrained = "true"/>
Person. HBM. xml
<One-to-one name = "idcard"/>

Many to many:
Create Table teacher_student {
Teacher_id int not null,
Student_id int not null,
........
........
Primary Key (student_id, teacher_id)
Foreign key ('student _ id') References 'student '('id') on Delete cascade on Update
Cascade,
Foreign key ('Teacher _ id') References 'teacher' ('id') on Delete cascade on Update
Cascade,
}
User-name)
The associated attribute is a persistence class of complex types, but it is not an entity. That is, no table in the database corresponds to this attribute, but the attribute of this class must be
Persistent Storage
<Component name = "name" class = "com. wuxiaoxiao. Name">
<Property name = "initial">
<Property name = "first">
<Property name = "last">
</Component>
When the component attributes cannot be easily matched with the fields in the table, you can choose to implement:
Org. hibernate. usertype. usertype or org. hibernate. usertype. compositeusertype
Set ing:
Set by default: No sequence or repetition is allowed.
List: ordered
List <employee> EMPs = new arraylist <> (employee );
Configuration: <list name = "EMPs">
<Key column = "depart_id"/>
<List-index column = "order_col"/> // keep order
<One-to-learn class = "employee"/>
</List>
// The order is not maintained.
<Bag name = "EMPs">
<Key column = "depart_id"/>
<One-to-learn class = "employee"/>
</Bag>
Map; has a key
Private Map <string, employee> EMPs;
<Map Name = "EMPs">
<Key column = "depart_id"/>
<Map-Key type = "string" column = "name"/>
<One-to-learn class = "employee"/>
</Map>
Employee emps1 = new employee ();
Emps1.set .....;
Employee emps2 = new employee ();
Emps2.set .....
Department depart = new Department ();
Depart. setemployee (SET );
S. Save (emps1 );
S. Save (emps2 );
S. Save (depart );
EMPs is a set attribute of department, so whether emps1 and emps2 can be saved by executing S. Save (depart ).
???
Yes: <set name = "EMPs" cascade = "Save-Update">
..........
</Set>
Is to add the cascade attribute.
Cascade and link maintenance:
. Cascade is used to describe whether to perform similar operations on the slave object of the main object when performing some operation on the main object.
:
None, all, save-Update, delete, lock, refresh, evict, replicate, presist, merge, delete-orphan (oen-
To-operate)
In general, cascade-to-one and cascade-to-sequence are not set, and cascade is set in <one-to-one> and <one-to-sequence>.
. Inverse table "do you want to discard maintaining associations" (the impact on database tables when two objects in Java are associated), in one--
Used in the collection definition of objects and objects-to-objects. Inverse = "true" indicates that the object does not maintain the association relationship. The value of this attribute is generally in
Set the value to false when an ordered set is used (note that the default value of Hibernate is false). One-to-one sequence is used to update the foreign key to maintain the association.
. Adding-to-sequence to maintain the Association is to add or remove records in the intermediate table.
Note: The objects configured with one-to-one do not maintain the association relationship.
The inverse attribute cannot appear in the list ....
Note:
Inheritance ing:
Video 29
We recommend that the number of tables not exceed the number of classes.
Load lazy loading:
User user1 = (User) Session. Load (userclass, ID );
Hibernate. initialize (user1 );
// User1 is not null
// Lazy loading is used to improve access efficiency and interact with the database only when necessary.
One-to-one lazy loading:
The following three conditions must be met to achieve lazy loading (no lazy loading when querying the primary object and lazy loading when querying the slave object ).
Load)
(Constrained = "true" does not exist in the primary table, so the primary table is not loaded lazily ):
Lazy! = False (lazy has another value of proxy) Constrained = true fetch = select
How can the fecth attribute be crawled? When does the lazy attribute be crawled?
One-to-pull: lazy! = False fetch = select
Failed-to-one: lazy! = Flase fetch = select
Upload-toyun: lazy! = False fetch = select
Objects that can be loaded lazily are rewritten proxy objects. When the associated session is not closed, access these objects
Object) properties (except GETID and getclass) hibernate will initialize these proxies, or use hibernate. initialize (proxy)
Initialize the proxy object. When the associated session is closed, an exception will occur when the access to the objects to be loaded is lazy.
The proper use of lazy loading can increase the access speed of the system !!!!
Cache:
For example, if a user reads user information and another user reads user information, the previous user reads the information from the database,
The latter user can not read data from the database, which improves access efficiency.
Example:
Static map cache = new hashmap ();
Public static user getuser (int id ){
String key = user. Class. getname () + ID;
User user = (User) cache. Get (key );
If (user! = NULL)
Return user;
User = getfromdb ();
Cache. Put (Key, user );
Return user;
}
Private user getfromdb (){}
If the information of the user is updated after the first user is checked
Public static void Update (User user ){
Updatedb (User );
String key = user. Class. getname () + User. GETID ();
Cache. Remove (key );
}
Public static void updatedb (){}
Hibernate Cache
Level 1 cache: Session-level cache
User user = (User) Session. Get (userclass, ID) // find from the database
System. Out. println (user. getclass ());
User = (User) Session. Get (userclass, ID); // search from the cache
System. Out. pritnln (user. getname ());
When the session is closed, the cache will disappear !!! Therefore, the cache function of the session is relatively small.
The Caching function is mainly used to improve the performance. It can be simply understood as a map. Using caching involves three operations: putting data into the cache
To retrieve data from the cache and delete invalid data from the cache.
Level 1 cache and session-level sharing
Save, update, saveorupdate, load, get, list. iterate, lock these methods will put the object in the first-level cache, first-level
Han Cun cannot control the number of caches. Therefore, when operating a large volume of data, memory overflow may occur. You can use the evict and clear methods.
Clear cache content!
Query and creaita cannot read data from the cache. Get and load can read data from the cache.
Secondary cache:
Hibernate uses a third-party cache.
Configure in the configuration file to tell hibernate what kind of cache to use
. <Property name = "cache. user_second_level_cache"> true </property> // notify hibernate that the second-level cache is enabled.
. <Property name = "cache. provider_class"> org. hibernate. cache. oscacheprovider </property> // tell
What level 2 Cache does hibernate use?
The oscacheprovider is selected, and the configuration file Oscache. properties should be placed under classpath.
. Tell hibernate which object to cache <class-Cache class = "..." usage = "read-write" (policy, if not
Modify the object and select read-only)/>
Another way is to specify the class to be cached: There is a cache before the mapped file ID: <Cache Usage = "read-write"/>
Hibernate first looks for the level-1 cache, but does not find it from the level-2 cache, but does not find it from the database.
View cache statistics: <property name = "generate_statistics"> true </property> // used during testing and deployed
Close
Use Statistics ST = hibetnateutil. getsessionfactory. getstatistics () in the Code ();
System. Out. println (St. getsecondlevelcachehitcount ());
You can view the information used by the second-level cache.
Level-2 cache, sessionfactory-level sharing
. Session save (this method is not suitable for native generation primary keys), update,
Saveorupdate, list, iterator, get, load, query, criteria all fill the second-level cache, but only (when querying the cache)
Session iterator, get, and load will fetch data from the second-level cache (iterator may have n + 1 queries)
. Query, criteria (query cache) because the hit rate is low, Hibernate is disabled by default. Modify cache. use_query_cache.
True to open the query cache and call query. setcacheable (true) or criteria. setcacheable (true)
Example: Query q = S. createquery (".....")
Q. setcacheable (true );
. Sessionfactory provides the evictxxx () method to clear the cached content.
. Open generate_statistics for statistics and use sessionfactory. getsatistics () to obtain statistics.
Distributed cache and central cache:
Cache conditions:
The number of reads must be greater than the number of modifications
The data volume cannot exceed the memory capacity
Have exclusive control over data
It can tolerate invalid data.
Transaction:
Jdbctransaction: a single database (one sessionfactory corresponds to one database), implemented by JDBC
Session session = NULL;
Transaction Tx = NULL;
Try {
Session = sessionfactory. opensession ();
Tx = session. begintransaction ();
// Process
TX. Commit ();
} Catch (hibernateexception e ){
If (TX! = NULL)
TX. rollback ();
Throw E;
} Finally {
If (session! = NULL) Session. Close ();
}
}
Jtatransaction: It can be simply understood as a cross-Database Transaction, implemented by the application JTA container; jtatransaction needs to be configured
Hibernate. transaction. factory_class parameter. The default value of this parameter is
Org. hibernate. trasaction. jdbctransaction. You must change this parameter when using jtatransaction.
Org. hibernate. trasaction. jtatransaction, and configure the JTA. usertransaction parameter JNDI name.
In jtatransaction, use this value to find javax. transaction. usertransaction in the context context of JNDI)
Javax. transaction. usertransaction Tx = context. Lookup ("jndiname ");
Try {
TX. Begin ();
// Session operations for multiple databases
// Session1 ....
// Session2 ....
TX. Commit ()
} Catch (exception e ){
TX. rollback ();
Throw E;
}
Transaction boundaries:
When to open and when to submit and when to roll back
Transaction Boundary Control at the business logic layer
Opensessioninview Mode
Solution: Transaction Boundary Control and lazy loading
Defect: the transaction has a periodic amplification, and the session has a periodic amplification,
MySQL concurrency is about 200, and Oracle concurrency is about 300.
Pessimistic lock and optimism
For example, if two administrators edit the same user information at the same time, if there is no lock, the submitted information will be overwritten by the submitted information.
Pessimistic lock: the user is locked when the user information is read. Other users can only wait until the lock is released, which is implemented by the database.
Optimistic lock: Implemented by hibernate using version and timestamp
Add the private int version field to the user class;
Add <version name = "version"/>
The session is non-thread-safe and has a short life cycle. It indicates a connection to the database. Generally, the session does not exceed one request in the B/S system.
Internal maintenance of level 1 cache and database connections. If the session is opened for a long time, it will occupy memory and database connections for a long time.
Sessionfactory is on-site security. A database corresponds to one sessionfactory and has a long life cycle. Generally, the system generates a VM
Valid within a period; sessionfactory stores information (user, password, URL) and ing information related to database connections, and
Some information required for running hibernate
Flush (): Synchronize the first-level cache in the session with the database (we recommend that you do not call it yourself)
Memory overflow may occur during batch data operations. The solution is as follows:
1. Clear the data in the session:
For (INT I = 0; I <100000; I ++ ){
S. Save (User );
If (I % 20 = 0 ){
S. Flush (); S. Clear ();
}
}
2. Use the statelesssession interface. It does not interact with the level-1 cache or level-2 cache, nor triggers any events, interceptors, listeners, and
The operation of this interface is immediately sent to the database. Like the JDBC function, statelesssession
S = sessionfactory. openstatelesssession (); the method of this interface is similar to that of session.
3.query.exe cuteupdate (): When batch update is executed, the related
Query q = session. createquery ("Update U set Birthday =: BD from user as U ");
Q. setstring ("BD", 1 );
Q.exe cuteupdate ();
Hql
1. query multiple objects: select art, user from article, user where art. Author. ID = user. ID and
Art. ID =: ID this method returns object [], object [0]: article, object [1]: User
2. Paging query. setfirstresult, query. setmaxresults, query. iterate ("select count (*)
From person "). Next ()
3.batch update query.exe cuteupdate () may cause invalid data in the second-level cache
Criteria
1. Sort criteria. addorder (order. DESC (propertyname ))
2. The link between criteria. setfetchmode ("propertyname", fetchmode. Select) and the ing File
The fetch function is consistent.
3. Projections. rowcount (), max (propertyname), AVG, groupproperty ....
4. pagination projections. rowcount (), criteria. setfirstresult (), criteria. setmaxresult ()
5. detachedcriteria (offline query, dynamic query) can be created outside the session (created at other layers, such as in service)
Then, use the getexecutablecriteria (Session) method to create a criteria object to complete the query.
Example: The query conditions are not fixed:
Public list DC (detachedcriteria DC ){
Session S = ....
Criteria c = Dc. getexecutablecriteria ();
List RS = C. List ();
S. Close ();
Return Rs;
}
Detachedcriteria Dc = detachedcriteria. forclass (user. Class)
String name = request. getparameter ("name ");
If (name! = NULL)
DC. Add (restrictions. eq ("name", name ))
List users = Dc (DC );
6. Example query, example. Create (OBJ); criteria. Add (example)
N + 1 queries and lazy loading:
Query. iterator (): Execute n + 1 queries. First, search for all IDs from the database and find records from the Database Based on each ID.
Changing the fetch capture attribute to join can avoid n + 1 Cache
Interceptor and event:
Both interceptor and event are extended mechanisms of hibernate, and interceptor interfaces are old implementation mechanisms. Now they are changed to event listeners.
All of them are hibernate callback interfaces. hibernate will call these classes in SAVE, delete, update... and so on, for example, we intercept
Stored events: Execute the event listener before the Save method is executed.
Public class savelisterner implements or. hintings. saveorupdateeventlister {
Public void onsaveorupdate (saveorupdateevent event) throws hibernateexception {
If (event. GetObject () instanceof CN. itcast. User ){
User user = (User) event. GetObject ();
Output the user name .....
}
}
}
Configure the listener in the configuration file:
<Event type = "save">
<Listener class = "org. hibernate. event. Def. defaultsaveorupdateeventlistener"/>
<Listener class = "com. wuxiaoxiao. savelisterner"/>
</Event>
SQL:
Select * from user: All SQL statements
Query q = session. createsqlquery ("select * from user"). addentity (user. Class );
List <user> rs = Q. List ();
For (User U: RS)
System. Out. println (U. getname ());
Name query:
Place query conditions in other places for unified management:
For example, in the ing file, configure it to be placed outside or inside the class.
<Query name = "getuserbybirthday">
<! [CDATA [from user where Birthday =: birthday]>
</Query>
Query by name in the Code:
Query q = session. getnamequery ("getuserbybirthday (outside)"); // (inside) package name. getuserbybirthday
Q. setdate ("Birthday", new date ())
Return Q. List ();
Unsuitable scenarios of hibernate:
. Not Suitable for OLAP (Online Analytical Processing) systems, mainly for querying and analyzing data; suitable for OLTP (online transaction processing)
Some old systems with unreasonable relationship model design cannot take advantage of hibernate.
. Systems with large data volumes and demanding performance requirements are also difficult for hibernate to meet the requirements, and the efficiency of batch data operations is not high.

This article is transferred from www.35java.com

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.