Hibernate phase Summary (i)

Source: Internet
Author: User
Tags rowcount in domain

Hibernate it is a framework for implementing an ORM (object-relational mapping) to the JDBC lightweight package. In the persistence layer of the project. Mainly learn its Hibernate API and Hibernate.cfg.xml, Object relational mapping file


Here are the components of the project:

Web tier

The Business Logic layer (call the HQL statement to manipulate the persistence layer so that you don't have to worry about which database to use, and the persistence layer will judge for itself)

DAO layer

Persistence layer (a lightweight encapsulation of JDBC to complete the operation of the database)

Database


There are three main processes for developing a hibernate: First, start with the domain object (also known as Javabean,pojo), and then write the Object relational mapping file and Hibernate.cfg.xml. Second, start with the DB, then write the object relationship mapping file and Hibernate.cfg.xml. Third, start with the Object relational mapping file. In general, the domain object class and the Object relational mapping file together, the main role of the Object relational mapping file is to establish a mapping relationship between the table and the domain class, the fields of the table, and the properties of the domain class. the Object relational mapping file is an XML file, so a DTD file is required to standardize it. It is also important to note to the package, to the class, and to the primary key (<id></id> represents the primary key, to indicate which attribute in the domain object is the primary key, and which field in the table corresponds to, and then specify the primary key's build policy, and the policy name), mapping the property. The role of Hibernate.cfg.xml is to specify which database to connect to, including the login user, password, database name, URL, and which object to configure. hbm.xm. mapping file.

In the operation of Hibernate, the first to establish a configuration file config (used to load hibernate.cfg.xml), and then set up a session factory Sesstionfactory, and then get one session, This session can be understood as the connection in JDBC, note that if you want to make additions or deletions to the database, we will use the transaction commit, and if it is only the query, we can not use the transaction.

Configuration configuration=newconfiguration (). Configure (Hibernate.cfg.xml);// Role of the configuration: 1. Loading hibernate.cfg.xml

Sesstionfactory sesstionfactory=configuration.buildsesstionfactory ();//sesstionfactory resident Memory

Session session=sesstionfactory.opensession ();

Transaction ts=session.begintransaction ();

Business operations

For example, add one (employee)

Session.save (employee);

Session.delete (employee);

For example, to modify a (employee), before this, we have to get a

Employee employee= (Employee) session.load (employee.class,3);

Employee.setname ("CGF");

Session.save (employee);

Here's a description: The Load method obtains the object by obtaining the primary key ID, and returns an object, so the conversion

TS.COMMT ();

It is emphasized here that Sesstionfactory is a heavyweight factory, connecting a database is usually just one, preferably writing it to a method of a class, which is the final type, the method is static, and is guaranteed to be called only once.

Auto-Generate table can be set in Hibernate.cfg.xml, <property name= "Hbm2ddl.auto" >create or update or Create-drop or Validate</property > Create: No table is created automatically, there is a table, first delete and then create. Update: No table, then create, there is a table, the first to determine whether the table structure has changed, there is no change in the update, there is a change, the first set up a new table. Create-drop: Automatically delete table when show off Sesstionfactory

Validate: Each time the data is inserted, the table structure is verified to be consistent.

In the object mapping relationship file, the primary key generation method, there are 7 kinds of common: sequence (oracle,mysql no this) increment (MySQL available), assigned (custom)

Compare session Creation Method: The first type: Opensession () creates a session new, and does not bind to the current thread, after the transaction commits to manually close the session; The second type of getcurrentsession () uses this method to create the session, which must be configured in Hibernate.cfg.xml <property name= "Hibernate.current_session_ Context_class ">thread</property> (the local transaction is configured here, and if it is a global transaction, the thread is changed to JTA.) The session created by a cross-database transaction called a global transaction is the same and is bound with the current thread, the session is automatically closed after the transaction commits or rolls back (rollback), but it is important to note that the query operation also commits the transaction.


The role of the session interface: 1. An instance represents a single operation with the database, including Crud 2. The thread is not synchronized (unsafe), so to ensure that it is used in the same thread, you can use Getcurrentsession ()

  

Compare get (), load () the difference between the two query methods: There are two main, first, get it will go to the cache first to check, not found, send a request to the database, if not found, then return null; second, load it does not immediately send a request to DB, and will not send a SELECT statement, If found or not found, a proxy object will be returned first, if the object to invoke the query later, then send the SELECT statement, if not found in the DB, the exception (the object does not find the exception), we call this phenomenon lazy loading. Lazy loading This phenomenon can be canceled, in the *.hbm.xml object mapping file <class name= "employee" lazy= "false" table= "Employee" > default is true; What they have in common: they will first look for data from the cache (cache session, and level two cache), and level two cache needs to be configured OH

Understanding the thread-local pattern Threadlocal.set (session) associates the thread with the session.

queries can also be used with query () and Criteria ()   Query Query=session.createquery (from Employee where name= "CGF");//Note Here The Employee is the domain class my class name, not the table name, will automatically map. List<employee>list=query.list (); for (Employee e:list)

Automatically generate domain and *.hbm.xml,hibernate.cfg.xml with MyEclipse. First set up the project, introduce Hibernate, and then the new driver module in Database Explorer Jdbc:oracle: THIN:@127.0.0.1:1521:ORCL, then find the table to be reflected, right-click an option, and then configure it.

HQL Statement 1 queryquery=session.createquery (select Name,sex from Employee) retrieves a partial property List list=query.list ()// Note here that the object class cannot be closed, Because the query is not complete.

for (int i=0;i<list.size (); i++) {

Object []obje= (object[]) list.get (i);

System.out.println (obje[0].tostring+ "" +obje[1].tostring)

}

Another method is obtained by means of an iterator iterator

Iterator It=query.iterator ();

while (It.hasnext ()) {

Object[]obje= (object[]) it.next ();

System.out.println (obje[0].tostring+ "" +obje[1].tostring)

}

HQL Statement 2 master Uniqueresult,having,group By,order by,


HQL Statement 3 Paged Query statement

1. Find out the total number of records rowcount session.createquery (select COUNT (*) fromemployee). Uniqueresult ();//Here is an object to be found, first ToString, Again Interge.parseint ();

2. Calculate the total number of pages pagecount= (rowCount-1)/pagesize+1;

3. Finally paging list<employee> list=session.createquery (from Employee). Setfisrtresult ((i-1) *pagesize). Setmaxresult (  pageSize). List (); Here is the following: Setfisrtresult () is a query starting from the first, the default is No. 0; Setmaxresult () indicates a total of several records to be queried

HQL Statement 40,000 change always the way to hold the Basic Law to the law broken million DAO with the Dalivan law

For many-to-many relationship mappings (Many-to-many) we can convert to (one-to-many) or (Many-to-one)


Hibernate is a three-way process developed in which a database can be automatically generated using Domain+*.hbm.xml, but is configured in Hibernate.cfg.xml. This has already been explained in the above.

When you write domain, you design a business-independent key ID, and a default constructor that has no parameters.

Three states for an object in hibernate:

Transient state: Not under the management of the session, and there is no record in the database

Persistent state: Under the management of the session, and there are records in the database

Free State: Under session management, but not recorded in the database

<many-to-one name= "Dept" column= "dept_id"/>//Description: Here Dept is the Class property from the object, dept_id is the foreign key name of the corresponding generated table, if not filled, the default is dept

<one-to-many> should do this to configure <set name= "Stud" >

<key column= "dept_id"/>

<one-to-many class= "Student"/>

</set>//in domain, we find a one-to-many object attribute, placed in set name, because it is mapped to many tables, so there are many table classes and the foreign key corresponding to its table


There are 4 ways to solve lazy loading:

First, set lazy= "false" in the mapping file

Second, in the program to add Hibernate.initialize (student.getdept ()//proxy object);

Third, using Opensessioninview when we are going to query an object, generally only return the normal properties of an object, when we want to use the object properties, only to the database again issued query request, then, for this phenomenon we call lazy loading

Fourth, in the SSH framework, in the service layer, through the annotation method to solve lazy loading


There are two types of <one-to-one> relationships: one is based on the primary key: The primary key from the table is the foreign key, and then a field (property) of the primary table is <one-to-one name= "mapped object property name" > (primary) The mapping file for the foreign key table. The primary key generation strategy is with foreign (foreign key), and you want to specify which property of the primary table the foreign key corresponds to <param name= "property" constrained= "true" > which attribute corresponds to the main table </param>

The other is based on a foreign key: a field (property) from the foreign key of the table to the primary table, and the mapping file for the primary table is unchanged, but for the mapping file from the table:

Change to <many-to-one name= "one field (property) of the primary table" unqiue= "true"/>


<mang-to-many> we convert it to <one-to-many> and <many-to-one> relationships and then press <one-to-many> and <many-to-one > Steps to

For cascading operations, we typically configure on <one-to-many cascade= "Delete or save-update or persist or merge" > and <one-to-one>, And usually on one side of one or the main object

For this message board Project 1.WEB Layer 2. Interface 3. Business Layer 4.DAO layer (e.g. Hibernateutil tool) 5. Persistence layer 6. The database uses interface programming to decouple the Web layer from the business layer, so that the Web layer does not change as the business layer changes

Opensessioninview is designed to solve lazy loading, because generally we call the service (for example, UserService) automatically shut down or manually close the session, and we in the V layer, we want to use the object properties, this will be reported lazy loading exception, Therefore, the opensessioninview was introduced by broadening the life cycle of the session. This is achieved by using filter.

public void DoFilter (Servletrequestrequest,servletresponse response,filterchain chain) {

try{

Session session = ... Sessionfactory.getcurrentsession ();//Get Session object Here you must use the Getcurrentsession () method to get the session, making sure that the thread is using the same session

tx = Session.begintransaction (); Open transaction

Chain.dofliter (Request,response); Passed to the next

Tx.commit (); Commit a transaction

}catch (Exception e) {

An exception occurred, rolling back the transaction

}

}//when a request arrives, it is first intercepted by this interceptor, and when the data is acquired and displayed on the V layer, it returns to the inside of the filter, at which time the transaction is committed and the session is closed.

The discussion of caching is important: Cache sub-level cache (Session level, no configuration required) and level two cache (Sessionfactory level, configuration required)

When we want to query the data, the program will go to the first level of the cache to find, if not to the database to find (not configured level two cache), when the database found in the data, the data will be placed in the first level cache. Of course, not all operations will store data in the first-level cache, only save,update,saveorupdate,get,load,list,iterator,lock will store the data in the first-level cache.

So, what is the operation that reads the data from the first level cache? Get,load. (if there is no corresponding data in the first-level cache, get will immediately send a request to the database, and load will return a proxy object until the query is made to the database until the object property is actually used)

* * Note that **:list will place objects in the first-level cache, but not from one-level cache. Query.list (), Query.uniqueresult (), and a primary cache has no protection mechanism, which fills up memory and causes memory overflow. At this point we can use clear (), evict () to clean. Evict () Clears an object, clear () clears all cached information.

The lifetime of the session cache is automatically deleted when the session is closed.


The commonly used level two caches are: oscache,ehcache,hashtable,

Second-level cache configuration: Configured in Hibernate.cgf.xml, configure 4 level two cache on, specify which level of two cache, you can specify the number of hits and misses, specify which domain with the two-level cache. There are 4 strategies for two-tier caching: Read-only,read-write (Default), Nostrict-read-write, Transcational. Then introduce it in the SRC directory, oscache.properties This file, as this is specified with Oscache level two cache.


Commonly used primary key growth strategy: Sequence,increment,uuid,foreign,assigned,native,identity

Hibernate phase Summary (i)

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.