Why is hibernate back from a proxy object?


Why is hibernate back from a proxy object?

1 、 What is ORM Frame ?
Answer: Object-Relational Mapping,AbbreviationsORM),The object-oriented development method is the main method of development in the business application development environment,Relational databases are the main data storage systems that permanently store data in a business class application environment. Relational data cannot directly express Multi-to Multi-association and inheritance relationships,What are the problems to consider in the design of the persistence layer,What persistent layer frames have you used?Representation of relational data in the database. Save data in memory in a relational database,And in the database,This involves saving the data in a removable storage device for future use,Object-Cartography of relationships(ORM)The commercial entity behaves like an object in memory,Main implementation of the mapping of program objects to data from the relational database.

2 、 Establishment of a uniform calendar of resources in terms of access to data? Systems generally exist in the form of software packages ?
Answer: What is called “Durable” The persistence layer is the relatively independent layer of the system devoted to the persistence of data,In simple terms,You can change the underlying implementation without modifying the Code (System of files 、 There are associations and inheritance relationships between objects in memory. The object-oriented development method is the main method of development in the environment of business application development.

The objectives of the design of the persistence layer include:
– Separation of the data storage logic, Provide an abstract data provider.
– Separation of the underlying implementations of access to data, objects and relational data are two representations of a commercial entity.
– Separation of resource management and scheduling, In devices that provide persistence support, such as message queues (Like a cache mechanism).
– Summary of data, Provides more object-oriented data operations .

The frame of the persistence layer has :
– Hibernate
– MyBatis
– TopLink
– Guzz
– jOOQ
– Spring Data
– ActiveJDBC

3 、 HibernateAverageSessionFactoryEst – what the wire is secure? SessionEst – what the wire is secure (Two Threads can share the same Session That’s it?)?

  • SessionFactory Corresponding to Hibernate A concept of data storage, It’s wireless., Can be accessed simultaneously by several threads .
  • SessionFactory Generally built only at startup. For requests, Better SaleFactory Encapsulated in Singleton mode for easy access .
  • Session Is a light, secure unthreaded object (Unable to share between session wires), It represents a work unit that interacts with the database .
  • Session This is by SessionFactoryCréé, It will be closed once the task is completed. Session Is the main interface of the persistent layer services provided outside .
  • Session Delay obtaining the connection to the database (This is – to say that they only have access when necessary. ). To avoid creating too much session, Can be usedThreadLocalOi.session Linked to common thread, This allows the same thread to always obtain the same session. Hibernate 3AverageSessionFactoryDegetCurrentSession () It is possible. .

4 、 HibernateAverageSessionDeloadEtget What is the difference between the methods? ?
Answer: The three main differences are as follows::
1 If no admissible file is found, getRetour of the methodenull, the method launches an exception.
2 get The method directly returns the entity class object, read The method returns an agent for an entity class object .
3 InHibernate 3Avant, get Data retrieval method in the first level cache only, If no corresponding data is found, the secondary cache is exceeded. , SQL Direct SQL Instruction full reading of the data; road The method retrieves the data from the secondary cache; DeHibernate 3Let’s go., get The method is no longer to write and not to read the L2 cache, It can also access the secondary cache .

** Description: ** Pourload () MethodsHibernateIt is considered that there must be data in the database which can be used in complete safety to delay loading, Launch an exception without data, And throughget () Data obtained by the method may not exist .

5 、SessionDesave () 、uupdate () 、merge () 、 () saveOrUpdate () Etpersist () How to make a difference? What is the difference??
Answer: Hibernate The object for three states: Transitories (transient) 、 Persistent state (persistent) And free state (detached).

An instance of a transient state can be called save () 、persist () OusaveOrUpdate () The method becomes persistent; Free instances can be called update () 、 saveOrUpdate () 、lock () Oureplicate () Become persistent .

save () Etpersist () Will trigger SQLDeINSERTDeclarations, Etupdate () Oumerge () Will trigger UPDATEDeclarations.

save () Etupdate () The difference is that a transient object becomes persistent, One is to transform a free object into a persistent state .

merge () The method can be completed save () Study () Function of the method, The intention is to merge a new state on an existing persistent object or to create a new persistent object.

Pourpersist () Methods, Follow the instructions of official documents :
1 persist () Method of persistence of a transitional case, However, there is no guarantee that the identifier will be immediately filled in the Persistence Authority. , The filling of the identifier can be postponed until more time ;
2 persist () The method guarantees that when called outside a transaction, it does not trigger INSERTDeclarations, When you need to encapsulate a long session process, persist () The method is necessary;
3 save () Unsecured method 2Article (s), He returns the identifier, So he immediately goes INSERTDeclarations, Whether inside or outside the transaction .

As for block () Methods etupdate () Method difference, update () The method consists in transforming an object which has changed the unmanaged state into a persistent state; lock () The way to do this is to transform an object which does not has not changed the unmanaged state into a persistent state .

6 、 Session Loading process for solid objects .
Answer: Session To load a solid object :
1 Session Before invoking the database query function, the search begins with the type of entity and the primary key in the level 1 cache, If the search for the L1 cache touches and the state of the data is legal, Direct return ;
2 If the L1 cache does not touch, And then…SessionSera in progressNonExistsRecording (equivalent to a black list of requests, A quick judgment can be rendered in the event of a double invalid request, To improve performance) Search in, SiNonExists The same query criteria exist in, Rappenull;
3 If the L1 cache request fails, the L2 cache is questioned, Returns directly if the L2 cache touches;
4 If none of the previous requests have been affected, To send SQLDeclarations, If the request does not find a corresponding record, add the request to SessionDeNonExists Recorded in, And return to null;
5 Configure and SQL The Declaration obtains ResultSet, And create the corresponding entity object;
6 Include objects in Session (Level 1 scale) Management ;
7 If there is a corresponding interceptor, To execute the onLoadMethods interceptor
8 If the secondary cache is activated and defined for use, Include the data objects in the secondary cache;
9 Turn over the data object .

7 、QueryInterfacelistMethods etiterateWhat is the difference between the methods??
Answer:
1 list(The method cannot use the level 1 cache and the level 2 cache (Write and do not read on the cache), He can only use the request cache if the query cache is activated ;iterate(The method can make the most of the cache, If destination data is read read-only or frequently ,Useiterate(The method can reduce general performance costs.
2 list () The method does not cause N + 1 Research questions, Etiterate () The method can cause N + 1 Research questions

** Description: ** About N + 1 Research questions, Can be referenced UNSCRn previous article 中Qu’est – quEN + 1Questriquérabé

8 、 Hibernate How to make the request for pagination ?
Answer: The request for pagination consists in querying the number of records of a table in the database. , When looking for pagination, there is a Category Page, There is one at the bottom. PageCategory, I made detailed comments. :

package com.entity ;
import javax.persistence.criteria.CriteriaBuilder;
public class Page {

/ ** * Among them are Page,perPageRows These two parameters are necessary to perform a pagination request * The reason is that: hibernateDansCriteria Or can - be QueryCes Two interfaces: All.setFirstResult(Integer firstResult) * EtsetMaxResult(Integer maxResult) * Here.firstResult Is the number of indexes at the beginning of each page: * The number of indexes at the beginning of each page is calculated as follows: : (currentPage-1) * perPageRows + 1, This is a relative index of 1 At the beginning) * MaisHibernateDansfirstResultIndex from 0At the beginning,So, danshibernate The number of indexes starting with each page is calculated as follows: * (currentPage-1)* perPageRows + 1-1 =(currentPge-1)* perPageRows. * * maxResult Is the maximum number of recordings that can be interviewed per page: This is - to - direperPageRows. * * Math.ceil (totalRows / perPageRows) == totalPages; // This is a formula for calculating the total number of pages based on the total number of recordings and the number of recordings per page. . * /
private Integer currentPage; // Current page
private Integer perPageRows; // Number of records per page
 private Integer totalRows; // Total records:
private Integer totalPages; // Total number of pages:
public Integer getCurrentPage () {

return currentPage ;
}
public void setCurrentPage (Integer currentPage) {

this.currentPage = currentPage ;
}
public Integer getPerPageRows () {

return perPageRows ;
}
public void setPerPageRows (Integer perPageRows) {

this.perPageRows = perPageRows ;
}
public Integer getTotalRows () {

return totalRows ;
}
public void setTotalRows (Integer totalRows) {

this.totalRows = totalRows ;
}
public Integer getTotalPages () {

total returnPages ;
}
public void setTotalPages (Integer totalPages) {

this.totalPages = totalPages ;
}
}

Downstairs.HibernateDeCriteira Interface for the request :

Corresponding entity class EmployeeThe Code for :

package com.entity ;
import javax.persistence.* ;
@Entity
@Table (name = "EMPLOYED")
public class Employee {

@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private int id ;
@Column (name = "first_name")
private String firstName ;
@Column (name = "last_name")
private String lastName ;
@Column (name = "salary")
private into salary ;
public Employee () {

}
public int getId () {

return id ;
}
public void setId (int id) {

this.id = id ;
}
public String getFirstName () {

return firstName ;
}
public void setFirstName (String firstName) {

this.firstName = firstName ;
}
public String getLastName () {

return lastName ;
}
public void setLastName (String lastName) {

this.lastName = lastName ;
}
public int getSalary () {

return salary ;
}
public void setSalary (int salary) {

this.salary = salary ;
}
}

// EMPLOYEE Creation The table is:

create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR (20) default NULL,
last_name VARCHAR (20) default NULL ,
salary INT default NULL,
PRIMARY KEY (id)
);

First by writing a profile: hibernate.cfg.xml To connect to the database ;

hibernate.cfg.xmlThe Code for:





com.mysql.jdbc.Driver
jdbc: mysql: //localhost: 3306 / test
root
130850a ,
10
true
org.hibernate.dialect.MySQLDialect
thread



By writing a HibernateDeutilCategory: HibernateUtilThe Code for :

com.util package ;
import org.hibernate.SessionFactory ;
import org.hibernate.boot.Metadata ;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {

private static final SessionFactory sessionFactory ;
private static ServiceRegistry serviceRegistry;
static {

try {

StandardServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder () .configure ("hibernate.cfg.xml") .build () ;
Metadata metaData =
new MetadataSources (standardRegistry) .getMetadataBuilder () .build () ;
sessionFactory = metaData.getSessionFactoryBuilder () .build () ;
} wrestling (Throwable th) {

System.err.println ("E Initial SessionFactory creation failed" + th) ;
throw new ExceptionInInInitializerError (th) ;
}
}
public static SessionFactory getSessionFactory () {

return sessionFactory ;
}
}

Finally, the Code of the request is established, The codes are as follows:

import com.entity.Employee;
import com.entity.Page;
import com.util.HibernateUtil ;
import org.hibernate.Criteria ;
import org.hibernate.Session;
import org.hibernate.SessionFactory ;
import org.hibernate.Transaction;
import java.util.List;
public class PaginationQuery {

public void paginationByCriteria () {

SessionFactory sessionFactory = HibernateUtil.getSessionFactory () ;
Session session = sessionFactory.getCurrentSession () ;
Transaction tx = null ;
try {

// do some work
tx = session.beginTransaction () ;
Page page = new Page () ;
/ ** * Suppose the first page is now questioned, The maximum number of records requested per page is 3. * /
page.setCurrentPage (1) ;
page.setPerPageRows (3) ;
Criteria criteria = session.createCriteria (Employee.class) ;
Integer currentPage = page.getCurrentPage (); // Get the current page
 Integer perPageRows = page.getPerPageRows (); // Obtain the number of records per page:
/ ** * InPage I explained in the class: The number of indexes per page begins to hibernate The calculation formula in is: (currentPage-1) * perPageRows * /
criteria.setFirstResult ((currentPage-1) * perPageRows) ;
criteria.setMaxResults (perPageRows) ;
List employees = criteria.list () ;
for (Employee employee: employees) {

System.out.println ("***********************");
System.out.println ("id =" + employee.getId () + "firstName =" + employee.getFirstName () + "lastName =" + employee.getLastName ()) ;
}
tx.commit () ;
} wrestling (Exception e) {

if (tx!= null) {

tx.rollback () ;
}
e.printStackTrace () ;
} finally {

session.close (); // Close the flow, make sure to close, Otherwise, the operating speed will be affected. .
}
}
public static void main (String [] args) {

PaginationQuery paginationQuery = new PaginationQuery () ;
paginationQuery.paginationByCriteria () ;
}
}

9 、 What is the lock mechanism for? ? Brief description Hibernate Pessimistic and optimistic locking mechanism .
hibernate Locking mechanism, Write a summary today. Hibernate The locking mechanism includes pessimistic and optimistic locks .

(1) Pessimistic lock

It is about being careful about how the data is changed. . Suppose the data is accessible at all times, maybe another customer has access to the same data. , To maintain data consistency, the data is therefore locked at the database level, implemented by the locking mechanism provided by the database .

Based on surjdbc The implemented database is locked as follows::

select * from account where name = "Erica" for update

In the update process, the database is locked, Any other operation on this data will be delayed . Unlock after the start of this transaction. Ethibernate The concrete implementation of the pessimistic lock is as follows::

String sql = "Request instruction" ;
Query query = session.createQuery (sql) ;
query.setLockMode ("Object", LockModel.UPGRADE) ;

Speaking of which, that’s what I said Hibernate Lockout mode :

  • LockMode.NONE: No locking mechanism.
  • LockMode.WRITE: HibernateInsertEtUpdate It is automatically acquired during registration .
  • LockMode.READ: Hibernate It is automatically acquired when reading the recordings .

These three locking modes are provided for: Internal hibernate, regardless of the database lock:

LockMode.UPGRADE: Use of the locked Phrase update database .

What we should note here, is that: Only before the start of the request (This is – to – direhernateGénérersqlBefore the Declaration) Lockout, Only by locking the database, The data passed without including for updataClausesql Instruction loaded , There is no locked database. .
But, in terms of system performance, For a single machine or a small system, this is not a problem. But if it’s a system on the web, , There will be a lot of connections at the same time , Suppose there are hundreds or thousands or more of simultaneous accesses ,What are we going to do? If we wait until the database is unlocked, we will do the following : , What resources are wasting – us? ? – This leads to an optimistic lock .

(2) The optimistic lock

Optimistic locking It is optimistic that problems of simultaneous access to data rarely occur. , Do not lock at the database, To maintain the right data, the optimistic lock adopts the logic of the application to carry out the version control .

For example, if you have two clients ,A The client first reads the balance of the 100Yuan account,AfterB The client also read the balance of the 100Metadata account,A The client removed 50Yuan, Changes to the database , The balance in the database is now 50Yuan,B The customer must also withdraw 30Yuan, Based on the information obtained, 100-30Sera70Solde, If the database is changed at this stage , The final balance will be incorrect .

Without a pessimistic lockout strategy, Once the data is inconsistent, there are several solutions, one is to update first, one is mainly updated, it is more complicated to check the modified data to implement them. , Or check all properties for an optimistic lock .

Hibernate Main update after verification of the version number ,And that too. Hibernate Recommended method , Add one to the VERSON column registration database , Read with version number when reading the data , And increment the version number when updating the data , Then compare the version number with the version number in the database , Update if it is greater than the version number in the database , If not, there will be an error. .

Take the previous example. ,A The client reads the balance of the 1000Yuan account, And read version number 5 together And yes,B The client also reads the account balance at this stage 1000Yuan, The version number is also 5,A The balance of the customer’s account after receipt of payment is: 500, The version number is added 1, The version number is currently 6, And the version number in the database is 5, Update , After updating the database , The balance of the database is now 500,The version number is 6,B Modify the database after receipt of payment by the customer ,Its version number is5, But the version number of the database is 6, Do not update at this time ,B. Customer data reread new database data and perform a new operational process to modify the database.

ParHibernate If the version number control is locked, Add one to our Properties version object, For example :

public class Account {

private int version ;....
public void setVersion (int version) {

this.version = version ;
}
public int getVersion () {

return version ;
}
....
}

And in the image file, We use optimization-lock Configuration of attributesversionControl, Add a label after the property bar, As follows:





....


After adjusting the version control , In the example above, if B The client has attempted to update the data ,Go triggerStableObjectStateException, We can seize this exception , Relate the data to the database during processing ,At the same time B Current customer data and data display in the database ,JeanB Customers have the possibility of comparing inconsistent data , To determine the part to modify , Or you can program to automatically read new data , And repeat the operational deduction process , Until the data can be updated , All of this can be done in context , Without your customers knowing .

But there are also insoluble problems with the optimistic lock: As we mentioned earlier, the implementation of an optimistic locking mechanism is often based on the logic of storing system data., Implementation in our systems, Updates to user balances of external systems are not controlled by our systems, Risk of updating illegal data in the database . So when we do e-commerce, pay attention to this problem. , Use a more reasonable logical verification, Avoid data execution errors .

Can also be used SessionDeload () Oulock () When the locking mode is specified for locking .

If the database does not support the specified locking mode, Hibernate An appropriate locking replacement is selected, Instead of dropping an exception .

10 、 Expatiate three States of entity Objects and their transformation Relationships .
Answer: Last updateHibernate In the Hibernate document The object defines four states (There are three states. , There are essentially three states to ask during an interview. ), Respectively.: Transitories (new, or transient) (1, or persistent) (managed) (state of swimming) And delete the state (removed, AvantHibernate None of the three states defined in the document have been deleted), As shown in the figure below, Just before. Hibernate The deleted statements in the document are considered transient .

  • Transitories: Whennew After a solid object, This object is instantaneous, This is – to – say that this object is only a memory zone which contains temporary data, If no variable refers to this object, And will be JVM Recycling of waste . This object contains data that has nothing to do with the database ,Unless SessionDesave(、 saveOrUpdate(、persist(、merge( Method of association of transient objects with the database , And insert or update the data in the database , This object is converted into a persistent object .
  • Persistent state: An instance of a persistent object has a corresponding record in the database, With a persistent identity (ID). For persistent objects deleteAfter the operation, the corresponding records in the database will be deleted, there is no longer any correspondence between the persistent object and the recording of the database. , The persistent object becomes a deleted state (Can be considered transient). After modification of the persistent object, Will not immediately synchronize in the database, until the database transaction is initiated .
  • Free: When Session It’s done. Close(、clear(、evict(Ouflush(After, Solid objects move from persistent to free state , The object has persistent identity values compatible with the corresponding records in the database , But because the object was deleted from the session , The object is not in the management of persistence , So he is free. (Also known as deflated state). Free objects are very similar to temporary status objects, it’s just that it also contains a persistent token .

** Advice: ** On this subject, InHibernate Official documents For a more detailed interpretation .

11 、 How to understand Hibernate Deferred loading mechanism for? In practice, Deferred Loading and Session How to manage closed contradictions ?

Deferred loading: The deferred loading mechanism is proposed to avoid unnecessary general performance costs, What is called deferred loading is when you really need data. , To actually perform the data loading operation. InHibernate The deferred loading of solid objects and collections is provided in, En plusHibernate3 The deferred loading of attributes is also provided in . Here are the details of these types of deferred loading .

(1) Deferred loading of solid objects :

For associated entities, it can be divided into two situations:
1 When the associated entity is several entities (including one to several (recorded a lot to a lot): The associated entity exists in the form of a collection, Hibernate Will be used PersistentSet 、 PersistentList 、PersistentSortedMapPersistentSortedSet Wait a collection to manage the entities loaded late . This is what happened. .
2 When the associated entity is a single entity (including one to one 、 Several against one): When Hibernate When loading an entity, the delayed associated entity will be a proxy object of dynamic construction .

If you want to use a deferred load on a solid object, Must be configured in the entity’s mapping profile, as follows:



......


ParclassDelazyThe property is defined at three times, to activate the entity’s deferred loading function . If we use the following code:

User user = (User) session.load (User.class, ”1”); (1)

System.out.println (user.getName ()); (2)

During execution (1) When, Hibernate No data request has been launched, If we now use some debugging tools (For example, JBuilder2005DeDebugOutils), Look at that. user Snapshot object memory, we’re going to be surprised. , The return can be User $ EnhancerByCGLIB $$$ bebed8986Type object, And its property is null, What is happening?? You remember what I said? road session(Methods, Returns the proxy class object of the entity object , The type of object returned here is User Proxy class object for object. InHibernate UsingCGLIB, To dynamically build a Proxy class object , And contains all the properties and methods of the target object in the Proxy class object , And all properties are assigned to null. Memory snapshots displayed by the debugger, We can see what’s really going on right now UserObject, is contained in the Proxy object CGLIB $ CALBACK_0.targetIn properties, When the Code is executed (2) When, Now called user.getName () Methods, It is at this time – where CGLIB Assigned recall mechanism, actually calledCGLIB $ CALBACK_0.getName ()Methods, When the method is called, Hibernate Check first. CGLIB $ CALBACK_0.targetThe property is null, If it is not empty, The target object is called getNameMethods, If empty, The request of the database is launched, Generate something like that SQLDeclarations: select * from user where id = ‘1’ ; To query the data, And build the target object, And assign it to CGLIB $ CALBACK_0.targetIn properties.

Here., Via an intermediate proxy object, Hibernate Implementation of the deferred loading of the entities, It is only when the user actually launches an action to obtain the properties of the object of the entity, It is only then that the database query operation will actually be launched . Thus, the deferred loading of the entity is carried out through the intermediate proxy class, Then only session.load () The method uses only the deferred loading of the entity, Because only session.load () The method returns the proxy class object from the entity class .

(2) Deferred loading of the collection type:
InHibernate In the deferred loading mechanism , Application to the type of collection , The meaning is most important , Because it is possible to considerably improve performance ,To this end,Hibernate A lot of efforts have been made ,These include JDK Collection Réalisation independent de , We are in a relationship of one to several , Defined to contain the associated object SetAll,It’s not java.util.Set Type or sub-type ,But…net.sf.hibernate.collection.SetType, Implementation using personalized collection classes, Hibernate Implementation of deferred loading of collection types . To use a deferred load on a type of collection, We must configure the section on associations of our classes of entities as follows::



......






By putting the property is defined attrue To activate the deferred loading function of a type of collection. Let’s look at the code below.:

User = (User) session.load (User.class, ”1”) ;
Adset collection = user.getAddresses (); (1)
Iterator it = addset.iterator (); (2)
while (it.hasNext ()) {

Address address = (Address) it.next () ;
System.out.println (address.getAddress ()) ;
}

When the program is executed (1) When, At this stage, no request is made on the associated data to load the associated data. , Only in progress (2) When, The actual data reading operation only begins, At this time – there, Hibernate Index will the admissible data in the cache, To find admissible solid objects .
Here, we are introducing a new concept —Data index, We will first go to the .InHibernate data index when the type of collection is cached in , Is cached in two parts , First hide all the entities of the idList collection, Then hide the physical object , Of these solid objects idList, This is called a data index. . When searching for a data index, If the corresponding data index is not found, there will be one. select SQL Implementation, Obtain admissible data , And build collections of solid objects and data indexes , Then returns a collection of solid objects , And include entity objects and data indexes in Hibernate In the cache of. On the other hand, If the corresponding data index is found , Extract from the idList data index,And then according to find the corresponding entity in the cache , Return of the cache if found ,If you can’t find it,At the beginning of the SQL Request. Here we see another problem, This problem can affect performance. It is the Collection type caching policy . If we configure the type of collection as follows::



......







Here we apply the configuration, If you use this policy to configure the type of collection, Hibernate Only the data indexes will be cached, Without caching of solid objects in the collection . Configure above to execute the following code:

User = (User) session.load (User.class, ”1”) ;
Adset collection = user.getAddresses () ;
Iterator it = addset.iterator () ;
while (it.hasNext ()) {

Address address = (Address) it.next () ;
System.out.println (address.getAddress ()) ;
}
System.out.println (“Second query.....”);
User 2 = (User) session.load (User.class, ”1”) ;
Collection it2 = user2.getAddresses () ;
while (it2.hasNext ()) {

Address address2 = (Address) it2.next () ;
System.out.println (address2.getAddress ()) ;
}

Execute this code, You will get an output similar to this one below :

Select * from user where id = ’1’ ;
Select * from address where user_id = '1' ;
Tianjin
Dalian
Second query ......
Select * from address where id = ’1’ ;
Select * from address where id = ’2’ ;
Tianjin
Dalian

We have seen, During the second execution of the request , Two pairs were executed address Request operation for the table ,Why this? This is because after the entity’s first shipment , Configuration of the cache policy by type of collection , Only the collection data indexes are cached , The solid objects in the collection are not cached , So the second time the entity is charged ,Hibernate Index of data found for the corresponding entity , But according to the data index , Unable to find the corresponding entity in the cache ,So…Hibernate Two were launched from the data index found select SQL Request operations for, It is a waste of performance. , How to avoid this? ? We must also specify a cache policy for entities of the Collection type, so we will configure the types of collections as follows::



......







At this momentHibernate The entities of the collection type are also cached, If you launch the code above again according to this configuration, You will obtain an output similar to this:

Select * from user where id = ’1’ ;
Select * from address where user_id = '1' ;
Tianjin
Dalian
Second query ......
Tianjin
Dalian

There will no longer be queries based on the SQLDeclarations data index, because the physical objects stored in the Collection type can now be obtained directly from the cache.
(3) Deferred loading of attributes
InHibernate3Average Introduces a New Character —— Deferred Loading of Properties, This Mechanism also provides a powerful tool for obtaining high performance queries . When reading large data objects ,For example :: InUserThere is an object listed, This field is a java.sql.ClobType, Contains information about the user’s CV , When we load the object , We have to load this field every time , Whether we really need it or not , And this type of reading of large data objects involves significant general performance costs. InHibernate3Average, We can delay the loading mechanism by attributes , We only get it if we really need to manipulate this field , To read the data in this field , To do this, we must configure our classes of entities as follows::



......



By lazy elements Ownership parameters to activate the deferred loading of properties ,InHibernate3 To delay loading of attributes , A class intensifier is used for Class Improved Document Processing , Improvement by an intensifier ,Yes, CGLIB Logic of the recall mechanism , Add an entity class , Here, we can see the deferred loading of the attribute ,Or byCGLIB To get there..CGLIB- Yes.Apache An Open source project for, This class library can be manipulated javaBytecode for Class, Dynamicly constructing class objects that meet the requirements according to the byte code . Depending on the configuration above, we will execute the following code:

String sql = ”from User user where user.name = ’zx’ ”;
Query query = session.createQuery (sql); (1)
List list = query.list () ;
for (int i = 0; i

During execution (1) When, Generates something like SQLDeclarations :

Select id, age, name from user where name = ’zx’ ;

At that time - there, Hibernate Will be recovered User Field data for all loading properties not delayed in the entity, During execution (2) When, Generates something like SQLDeclarations :

Select summary from user where id = ’1’ ;

A pair is launched resumes Actual reading operation of field data .

12 、 Let's take an example of multiple to multiple association, and how to achieve Multi-dependent mapping .
Answer: For example: Products and orders 、 Students and courses are typical of multiple to multiple relationships . Can be used on an entity class @ManyToManyAnnotation configure several to several associations or configure several to several associations via and Tag in the mapping file, But in the real development of the project ,Most of the time, it is produced by converting Multi - associations mappings into two Multi Mappings - associations.

13 、 Talk about your understanding of inheritance mapping .
Answer: There are three strategies for mapping inherited relationships:
1 A table by inheritance structure (table per class hierarchy), Regardless of the number of sub-class, use a table.
2 One table per sub-class (table per subclass), Public information, Separate table for specific information.
3 One table per specific class (table per concrete class), There are as many sub-classes as there are tables..
The first method belongs to a single table strategy,The advantage is that no table connection is necessary when questioning objects of sub-class,Quick search,Suitable for polymorphic requests;The downside is that it can cause large tables. The last two methods are Multi-table strategies,The advantage is compact storage of data,The downside is that a connection request is required,Not suitable for polymorphic queries.

14 、 Brief descriptionHibernateCommon optimization strategies.
Answer: The answer to this question should be the optimization strategy you have used. , The most common are:
1 Develop a reasonable caching policy (Cache L2 (Application Cache).
2 Adopt a reasonable approach SessionManagement mechanisms.
3 Use the delayed loading characteristics as much as possible .
4 Define reasonable batch processing parameters .
5 If possible., Choose UUID As a primary key generator .
6 If possible., Replace the pessimistic lock with an optimistic lock based on the version number .
7 During development, Ouvthibernate.show_sql Options display SQL results, To understand what is happening below; Disable this option once development is complete .
8 Consider optimizing the database itself, Rational Index 、 Appropriate appropriate data partitioning policies, etc., can bring significant improvements to the efficiency of the persistence layer, but they need DBA (Database Administrator) professionals to provide support.

15 、 A word. Hibernate Level 1 ax for 、 Secondary cache and query cache .

What is a cache?
The cache is between the physical data source and the application , Is to copy a copy of the database data in a temporarily stored container , It is designed to reduce the number of times the application accesses a source of physical data , Improves the performance of the .Hibernate application when reading the data , Request in the corresponding cache according to the cache mechanism , If the required data is found in the cache ( It's called "Hide the Average Life") Use the data directly as a result , Avoid massive SQL shipments Loss of instruction performance at the database query .

Providing caching policies:

OfferHashTableCache,EHCache,OSCache,SwarmCache,jBoss Cathe2, These caching mechanisms ,Among them EHCache,OSCache Yes cannot be used in a grouped environment (Cluster Safe) De,And SwarmCache,jBoss Cathe2It's good.HashTable The cache is mainly used to test , Only objects can be stored ,EHCache,OSCache You can put objects in memory (memory) Average, You can also place items on your hard drive (disk) Come on.(Why on the hard drive? ? It is explained above. ).

HibernateClassification of the cache :

(1) SessionCache (Also known as transaction cache): Hibernate Integrated, Impossible to dismantle .

Cache range: The cache can only be current Session Access to objects. The life cycle of the cache depends on SessionThe life cycle of, When SessionAfter closing, The cache ends the life cycle .

(2) SessionFactoryCache (Also called application cache): Use of plug - third ins, Pluggable.

Cache range: Hide everything in the scope of application session Sharing, DifferentSessionCan share.Cessession Can - be a simultaneous access cache, The cache must therefore be updated . The life cycle of the cache depends on the life cycle of the application. At the end of the application, the cache ends its life cycle, The cache L2 exists at the scale of the application .

Level 1 cache :
Hibernate Some actions related to level 1 cache (Time point) :

Data caching :

  • save (), Quandsession Object call () Method after saving an object, The object is placed in session In the cache of.
  • get () Etload (), Quandsession Object callget () Ouload () Method after extracting an object from the database, The object is also placed in session In the cache of.
  • UseHQLetQBC Wait to query the data in the database .

For example: The database has a table as follows::

Useget () Ouload () Prove the existence of the cache :

public class Customer {

public static void main (String [] args) {

Session session = HibernateUtil.getSessionFactory () .openSession () ;
Transaction tx = null ;
try {

/ * Open a transaction * /
tx = session.beginTransaction () ;
/ * Obtain from the databaseid = "402881e534fa5a440134fa5a45340002" DeCustomerObjet * /
Customer customer1 = (Customer) session.get (Customer.class, "402881e534fa5a440134fa5a45340002") ;
System.out.println ("customer.getUsername is" + customer1.getUsername ()) ;
/ * Presentation of transactions * /
tx.commit () ;
System.out.println ("-------------------------------------------------------") ;
/ * Open a new transaction * /
tx = session.beginTransaction () ;
/ * Obtain from the databaseid = "402881e534fa5a440134fa5a45340002" DeCustomerObjet * /
Customer customer2 = (Customer) session.get (Customer.class, "402881e534fa5a440134fa5a45340002") ;
System.out.println ("customer2.getUsername is" + customer2.getUsername ()) ;
/ * Presentation of transactions * /
tx.commit () ;
System.out.println ("-------------------------------------------------------") ;
/ * Compare twoget () If the object obtained by the method is the same object * /
System.out.println ("customer1 == customer2 result is" + (customer1 == customer2)) ;
} wrestling (Exception e) {

if (tx != null) {

tx.rollback () ;
}
} finally {

session.close () ;
}
}
}

Output results from the program console :

Hibernate :
select
customer0_.id as id0_0_,
customer0_.username as username0_0_,
customer0_.balance as balance0_0_
from
customer customer 0_
where
customer0_.id =?
customer.getUsername islisi
------------------------------------------
customer2.getUsername islisi
------------------------------------------
customer1 == customer2 result is true

The principle is that: In the same Session Inside, First call () Methods, Hibernate First recover if the search object exists in the cache, No., HibernateServoirSELECT Instruction extract the corresponding object in the database, Then put the object in the cache, For the next time, Second call () Methods, Hibernate Recover first if the search object exists in the cache, Found exactly the research object, It comes out of the cache. , No longer retrieve from the database, Not sent again selectDeclarations.

Data deleted from the cache :

  • evit () Erases the specified persistent object of the cache, Release the memory resources used by the object, Specifies that the object passes from a persistent state to an unmanaged state, To become a free object .
  • clear () Clear all persistent objects from the cache, Free up the memory resources it uses .

Other cache operations:

  • containers () Determines if the specified object exists in the cache .
  • flush () Refresh the contents of the cache, Synchronize with the data from the database .

L2 :

@Test
public void testCache2 () {

Session session1 = sf.openSession (); // ObtainSession1
session1.beginTransaction () ;
Category c = (Category) session1.load (Category.class, 1) ;
System.out.println (c.getName ()) ;
session1.getTransaction ().commit () ;
session1.close () ;
Session session2 = sf.openSession (); // ObtainSession2
session2.beginTransaction () ;
Category c2 = (Category) session2.load (Category.class, 1) ;
System.out.println (c2.getName ()) ;
session2.getTransaction ().commit () ;
session2.close () ;
}

When we restart Session, Second CallloadOuget The method rediscovers the database when it retrieves the same object, Yes.selectInformation on the Declaration.

Reasons: Unsession Impossible to take the other session Cow in.

Performance problems: If it is a simultaneous multithreaded access CategoryCet object, readAn object, This pair could have been stored. , But because it's multithreaded, Is distributed differently in the middle, So, each time you get it back in the database, This can lead to poor request performance .

Solutions: Use of secondary cache.

What is the secondary cache?
SessionFactory Level Cow, Can Cross Exist Session, May Be Partered Session.

Suitable for secondary caching :

(1) Often visited

(2) Few changes

(3) Limited number

(4) Unsignificant data, Allow occasional competition of data .

These data are perfect for hiding in the secondary cache .

User permissions: Small number of users, Limited permissions, Will not be changed often, Often visited .

For example, organization .

Think: What kind of class? , The objects inside are suitable for the secondary cover?

Frequent changes, There are a lot of objects in the class, BBS Lots of messages, These messages 20,000 Several, which is cached, Not sure.. Unless you are sure there are frequent visits, the amount of data is not large, Very few changes, These data are perfect for hiding in the secondary cache .

Principle of implementation of the L2 cache :
Hibernate How to put the database data in the secondary cache? Warning!, You can consider the cache as a MapObjet, that's it...KeyFor storing OID objects,ValueFor storagePOJO. First of all,When using Hibernate Extract data from the database , After obtaining the recovered data ,Hibernate Object to recover OIDIn the Average cachekey, And then there will be POJOMetter in Average Value, Wait until you question the data next time ,Hibernate According to your OID offer Recover level 1 cache first , If the secondary cover is present and configured , Recover the secondary cache , Send to the database if you have not already made SQLDeclarations, Then put the object questioned in the cache .

Use of secondary cache

(1) Open the L2 cache:

For Hibernate Configure the secondary cache:

In the main hibernate.cfg.xml profile:


true

org.hibernate.cache.EhCacheProvider

Or when hibernateAvecSpring Directly after integration SpringProfilapplicationContext.xmlAverage





com / lp / ecjtu / model / Employee.hbm.xml
com / lp / ecjtu / model / Department.hbm.xml




hibernate.dialect = org.hibernate.dialect.OracleDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.cache.use_second_level_cache = true
hibernate.cache.provider_class = org.hibernate.cache.EhCacheProvider
hibernate.generate_statistics = true



(2) Configurationehcache.xml










(3) The use of the L2 cache requires annotations in the entity class:

Besoinehcache-1.2.3.jarSac :

I need it. commons_loging1.1.1.jarSac

The secondary utility cover can be configured by annotation in an entity class:

@Cache (use = CacheConcurrencyStrategy.READ_WRITE)

Load Default secondary cache, It's when you look at an object, It goes first to the level 2 cache. , If found, it will not go into the database. .

Iterator The secondary cache is also used by default, If this is the case, it will not go to the database. , Do not send select The declaration is.

List Add data to the default L2 cache, If there is a unquery, the data is removed and cached at level 2. , However, during the execution of the request, there is no search in the secondary cache, Search in the database . For every reason query The query criteria are different in .

(4) Or in an object which must be cached hbm Add a sub-label under the label in the file:

 












There is a relationship from one to several , You want to hide the associated parties when acquiring a game , Add a sub-label under the required Reset attribute , Here, you must associate hbm The file must also be labeled under the existing label ,No, Hibernate Hide only OID .


















16 、 HibernateAverageDetachedCriteria What the class does? ?
Answer: DetachedCriteriaEtCriteria The use of, But...CriteriaC is bySessionDecerateCriteria () Created by the method, which means leaving the one who created it. Session, CriteriaI can't use it..DetachedCriteriaNo need.SessionTo create (UtilizeDetachedCriteria.forClass () Creation of methods), It is therefore often called offline Criteria, And when a request is necessary SessionBIND (Call - le.getExecutableCriteria (Session) Methods), Which means DetachedC bonde differentFrita.

17 、 @ OneToManyAnnotatedmappedByQue do the attributes??
Answer: @OneToMany Used to configure one to several associative cards ,But usually, One to several association cards are maintained by more than one party , For example, students and classes ,Class attributes should be added to the student class to maintain the student-class association (In the database, the class number of the foreign key in the student table is used to maintain the relationship from several to one between the student table and the class table), If you want to use a bidirectional combination , Add a container attribute to the classroom to store students ,And use @ OneToMany Annotation for cartography ,Right nowmappedBy Attributes are very important. If you are using XMLConfigure, Can be labeled reverse = "true" Settings to achieve the same effect .

18 、 MyBatisUtilized in#And$ What is the difference between writing a placeholder?
Answer:#Process incoming data as a string, Incoming data is automatically quoted$ Display incoming data directly in SQL Average. Warning!:Use$ Substitutes can cause SQL Injection attacks, it works# Do not use where $, Write.order by The clause must be used $Instead of#.

19 、 Explain - me.MyBatis Medium namespace (namespace) The role of.

In the previous version MyBatis Average, Space of names (Namespaces) It didn't do much - thing. , Is optional. But now, as the namespaces become larger, you need to specify a namespace .

The namespace has two functions, one is to use longer fully qualified names to isolate different declarations. It also implements the interface link you see above . Even if you think you don't have an interface link yet, you should follow the rules here too. , In case you change your mind. . In the long term, just place the Java namespace correctly in the package namespace, Your code will be cleaner, It is also useful for easier use MyBatis.

Names resolution: To reduce the input quantity, MyBatis For all the configuration elements named (Include declarations, Distribution of results, Ax, etc.) The following naming resolution rules are used .

  • Full Name (For example, “com.mypackage.MyMapper.selectAllThings) Will be used directly to find and use .
  • Short name (For example, “selectAllThings”) If it is unique worldwide, it can also be used as a separate reference. . If it is not unique, Have two or more identical names (For example, “com.foo.selectAllThings” And “com.bar.selectAllThings”), The result is “Short names are not unique” Error, In this case, you must use a fully qualified name .

20 、 MyBatisDynamics enSQLWhat does that mean ?
Answer: For certain complex requests , We can specify several query criteria , But these conditions may or may not exist ,For example, in58 Find a house at the top of the city , We can specify an area 、 Floor and location to find the source , An area can also be specified 、 、 、 、 Type and location of the house to find the source of the house , This requires a dynamic generation based on the criteria specified by the SQLDeclarations user. If we do not use a persistent layer frame, we may need to assemble ourselves - same SQLDeclarations, It's goodMyBatis Provides an SQL dynamic To solve this problem. MyBatis For the implementation of the SQL dynamics The main elements of :
- if
- choose / when / otherwise
- trim
- where
- set
- foreach

Here is an extract from the mapping file .

 

Of course, you can also write like this. .

 

Look at the example below. .

 

21 、 What is it - what IoCEtDI? How it was done??
Answer: IoC Called control reversal ,- Yes, inversion of ControlAbbreviation of,DI (Dependency Injection) Called dependency injection ,That's right. IoC A simpler interpretation. The inversion of control consists in giving the container the right to call objects which are traditionally controlled directly by the Program Code,Assembly and management of the components of the object by container. What is called "Inversion control" is the transfer of control of the component object ,Transferred from the Program Code itself - even to the external container, Create objects by container and manage the dependencies between the objects .IoC Incarnate the principles of Hollywood - "Don’t call me, we will call you ”. The basic principle of the dependency injection is that the application component should not be responsible for finding resources or other dependent collaborative objects. The container is responsible for the configuration of the objects , The logic of finding resources must be extracted from the Code of the application component , Delivered to the container to complete. It is true. IoC Description more precise ,This means that the dependencies between the components are determined by the container at the time of execution, In terms of image , This is - to say - that the container dynamically injects dependence into a component .

For example,: A classA Interface required BMethods, So you must be an AAnd interfacesB class Establish an association or an addiction , The most primitive method is in class A Create an interface in BC Implementation Class for example, But this approach requires developers to maintain their own dependencies ,This is - to say - to modify the Code and rebuild the whole system when the dependencies change. If you manage these objects and their dependencies through a container, You only need A Defined for the associated interfaces BMethod (Manufacturer or setterMethods), ClassAAnd interfacesBClasse of implementation for C In a container, The Association of Two is carried out by configuring the container .

The dependent injection can be carried out by setterInjection of the method (Discharge point injection) (The manufacturer's injection and the interface injection are implemented in three ways ,SpringSoutiensetter Injection and injection from the manufacturer , The manufacturer's injection is generally used to inject the necessary dependencies , For optional dependencies ,Ettling Injection is a better option ,setterInjection requires that the class provide a manufacturer without parameters or a static factory method without parameters to create an object.

22 、SpringMoyenneBeanWhat is the range of ?

Spring 3 Bean mid-defined5 Medium-sized range, Respectively: single-wave (single case) (prototypes) (requests) 、 (session (Digital session) 5 The range of species is described below. :

  • singleton: Singleton Mode, Spring IoCIL will only have one split in the BeanExample container, No matter the BeanCite number - the., Always point to the same object. SingleThe scope isSpringChamp of application by default in, You can also display BeanDéfini as follows: singleMode, Configure as :

  • prototype: Prototype mode, Each passageSpringAcquisition of PrototypeDefinibeanHeure containers, The containers will create a new BeanExample, Each The authorities have their own properties and states, Etsingleton There is only one object worldwide. , Yes, statefulUtiliserprototypeChamp application, And for.

  • request: Once Http Request in progress, The container returns thisBean Same example of. And for the different HttpThe request produces a new Bean, And it is currently only Http Request Internal efficiency.
    , For each time HttpDemande, Spring The container conforms to bean To create a new instance, And the instance is currently HttpValable in the request, Other requests do not see the change of state in the current request, Currently HttpFin of the request, Lebean The Authority will also be destroyed .

  • session: Once Http SessionAverage, The container returns thisBean Same example of. And for the different Session The request creates a new instance, the current Mechanism only Session Internal Efficiency.
    , Same thing. Http Identical request, Each timesession Request for creation of a new body, The properties are not shared between different bodies, And the body is only available in its own session Valable in the request, End of the request, The Instance will be destroyed.

  • global Session: In a global context Http Middle Session, The container returns thisBeanThe same instance of, Only used in contextual context It works..

23 、 Explain to me what it is. PDO (Tangent oriented programming) ?
Tangent AOP programming In the spirit of, the basic operational functions and the cutting functions are developed separately., Then, the cutting functions and the basic operational functions “Tricot” Together, it's called AOP

PDO Subject :
AOPCapable to isolate, Logic or responsibility invoked jointly by the operational modules (For example, transaction 、 Management of newspapers 、 Control of authority, etc.) Packed up., Facilitate the reduction of duplicate codes in the system, Reduce the coupling between modules, And is favorable to the extensibility and the future maintainability.

PDO The concepts :

  • Entry point (Pointcut)
    In which classes, What methods (where)
  • Notification (Advice)
    What really happens in the method (when: Before the method / After the method / Before and after the method) What are you doing?(what: Improved functions)
  • Tangent (Aspect)
    Tangent = Entry point + Notification, The common point is: When?,Or?, How to improve !
  • Weaving
    Add a tangent to an object, Proxy object creation process.(By Spring To finish)

Example:
For a better PDO illustration The concept of, Let's take a practical example. :

In the example above, the main activity of tenants is to sign contracts. , Drill the rent, So that's enough. , The gray framed parts are repetitive and marginal, Leave it to the Agency. ,That's it. PDO An idea to: Separate the Code of Concern from the Works Code!

Actual code :

We will feel it in Code.

1.In Package 周pojo ⁇ New followingLandlord ⁇ Category:

package pojo ;
import org.springframework.stereotype.Component;
@Component ("landlord")
public class Landlord {

public void service () {

// It is simply a question of implementing the basic operational functions.
 System.out.println ("Sign the contract") ;
System.out.println ("Drink the rent") ;
}
}

2.In Package 玉aspect ⁇ Create a new intermediary 玉Broker ⁇ Category:

aspect package;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect ;
import org.aspectj.lang.annotation.Before ;
import org.springframework.stereotype.Component;
@Component
@Aspect
class Broker {

@Before ("execution (* pojo.Landlord.service ())")
public void before () {

System.out.println ("See room with the tenant") ;
System.out.println ("On prices") ;
}
@After ("execution (* pojo.Landlord.service ())")
public void after () {

System.out.println ("Hand Key") ;
}
}

3.In applicationContext.xml Configuration of automatic injection in, And say Spring IoC Where the container goes? Bean :







4.In Package 玉test ⁇ Write the Test Code below:

test package;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Landlord ;
public class TestSpring {

public static void main (String [] args) {

ApplicationContext context =
new ClassPathXmlApplicationContext ("applicationContext.xml") ;
Landlord landlord = (Landlord) context.getBean ("landlord", Landlord.class) ;
landlord.service () ;
}
}

5.Results of implementation :

 See the room with the tenant
On prices
Sign the contract
Drill the rent
Hand key

This example uses some annotations, It's good not to be able to read it now. , But we can see it from above, We are there. Landlord Service () The method only implements the Basic Company Code, The rest of the focus function is automatically completed depending on the section we have defined .

Use annotations to develop Spring PDO
The use of annotations has become common, so we use the example above to illustrate how to develop with Spring PDO annotations

First step: Select a connection point
Spring East at the PDO Frame method, We also use a certain amount of class and a certain method as a connection point. Another way to say it is: Choose which class and which method to use to improve functionality .

....
public void service () {

// It is simply a question of implementing the basic operational functions.
 System.out.println ("Sign the contract") ;
System.out.println ("Drink the rent") ;
}
....

We choose the above here Landlord In the service class () Method as connection point .

Second step: Create a section
Once the connection point has been selected, the Section can be created. We can consider the section as an interceptor, When the program is executed at the connection point, Intercepted. , Initialization method added at the beginning, I added the destruction method at the end. , In Spring Use only @Aspect Annoter a class, So Spring IoC The container will think it's a cut. :

aspect package;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect ;
import org.aspectj.lang.annotation.Before ;
import org.springframework.stereotype.Component;
@Component
@Aspect
class Broker {

@Before ("execution (* pojo.Landlord.service ())")
public void before () {

System.out.println ("See room with the tenant") ;
System.out.println ("On prices") ;
}
@After ("execution (* pojo.Landlord.service ())")
public void after () {

System.out.println ("Hand Key") ;
}
}

Warning!: The class defined as tangent is always a Bean, Besoin @ Component Annotation

The annotation on the method in the Code section gives an approximate idea of the name. , Here is a list Spring In AspectJ Notes :

Notes Description
@Before Pre - notification, Called before the connection point method
@Around Notification surround, It will overwrite the original method, But allows you to invoke the original method by reflection, We will talk about it later.
@After Post - notification, Called after the connection point method
@AfterReturning Return to notification, Called after the execution of the connection point method and its normal return, Require that the connection point method presents no exceptions during execution
@AfterThrowing Emergency notice, Called when the connection point method is abnormal

@BeforePre-notification, Called before the connection point method
@AroundSurround notification, It will overwrite the original method, but allows you to invoke the original method by reflection, We will talk about it later.
@AfterPost - notification, Called after the connection point method
@AfterReturningReturn to notification, Called after execution of the connection point method and its normal return, Require that the connection point method presents no exceptions during execution
@AfterThrowingNotice of exception, Called when the connection point method is abnormal

With the table above, we knew it. before () The method is the method called before the call of the connection point method, Et after () It is the opposite. , These annotations use regular formulas that define the tangents, which means Spring PDO What methods should be used to intercept which objects, and that's it. .

Third step: Define the tangents
Defined in the notes above execution Regular expression for, Spring. Using this regular expression, we can determine which class and which method to intercept :

execution (* pojo.Landlord.service ())

Analyze this expression in turn:

  • execution: Is triggered when it represents a method of execution
  • * : Method representing any type of return
  • pojo.Landlord: Full name of the representative class
  • service (): Name of the intercepted method

By the expression above, Spring We will know that it must be intercepted. pojo.Lnadlord Sub-service class () Methods. The demonstration class above is fine. , If you need to write more than one expression like this, it can be a bit complicated. , We can use @Pointcut Annotation to define a tangent point to avoid such a problem:

aspect package;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect ;
import org.aspectj.lang.annotation.Before ;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
class Broker {

@Pointcut ("execution (* pojo.Landlord.service ())")
public void lService () {

}
@Before ("lService ()")
public void before () {

System.out.println ("See room with the tenant") ;
System.out.println ("On prices") ;
}
@After ("lService ()")
public void after () {

System.out.println ("Hand Key") ;
}
}

Fourth step: PDO tests
Write the Test Code, but I'm here because JDK Version incompatibility appears BUG ... (Embarrassing ...)

So tell us: The configuration of the environment is important ... It is inexplicable. BUG It made you crack. ...

Surround notification
Let's talk about surround notification. , It's Spring PDO The most powerful notification, Because it incorporates pre-notification and post-notification, It retains the function of the original method of the connection point, so it is powerful and flexible, let's see.:

aspect package;
import org.aspectj.lang.ProceedingJoinPoint ;
import org.aspectj.lang.annotation.Around ;
import org.aspectj.lang.annotation.Aspect ;
import org.springframework.stereotype.Component;
@Component
@Aspect
class Broker {

// Previous note @Before And @After Notes and corresponding methods
 // @Before ("execution (* pojo.Landlord.service ())")
// public void before () {

// System.out.println ("See room with the tenant") ;
// System.out.println ("On prices") ;
//}
//
// @After ("execution (* pojo.Landlord.service ())")
// public void after () {

// System.out.println ("Hand key") ;
//}
// Use @Around Annotation to complete notifications before and after
 @Around ("execution (* pojo.Landlord.service ())")
public void around (ProceedingJoinPoint joinPoint) {

System.out.println ("See room with the tenant") ;
System.out.println ("On prices") ;
try {

joinPoint.proceed () ;
} wrestling (Throwable throwable) {

throwable.printStackTrace () ;
}
System.out.println ("Hand Key") ;
}
}

Execute the Test Code, The results are always correct:

 See the room with the tenant
On prices
Sign the contract
Drill the rent
Hand key

Use XML Development of the Spring PDO configuration

Annotations are powerful. , But based on XML We still have to understand, let's see. PDO Configurable elements in :

aop: advisorDefinition PDO Notification A very old way, Rarely used
aop: aspectSet a section——
aop: beforeDefine advance notifications——
aop: afterDefine post-notifications——
aop: around Define surround notifications——
aop: after-returning Define return notifications——
aop: after-throwingDefine exception notifications——
aop: configUp PDO Configuration elementsPDO The configuration of
aop: parents-declare Introduce a new additional interface for notifications, Improvements——
aop: pointcutDefine the tangents——

With the experience of the previous writing by annotation, And with the watch above, We rewrite the example above as follows: XML Easy configuration (Delete all annotations) :














Execute the Test Program, See the good results :

 See the room with the tenant
On prices
Sign the contract
Drill the rent
Hand key

24 、 Spring What are the automatic assembly methods in?
Answer:
- no, This option is spring Default options for frames, Indicates that automatic assembly is disabled OFF. We must be used in the definition Label explicitly define dependencies .

  • byName, This option activates bean Injection of dependence for the name .InBean When automatically assembling the properties, The name of the property is used to search for a match in the BeanDefinition profile. If you find something like that, bean, inject it into the properties . If you can't find bean, an error is made .
  • byType, This option supports bean Injection of dependence type. Inbean When automatically assembling properties, The type of property class is used to search for a match in the beanDefinition configuration file. If you find something like that, bean, inject it into the attribute . If not, bean, An error is made .
  • constructor, Automatic assembly and byTypeSimilar, Only for manufacturer's parameters . When automatic assembly is activated BeanMoyenne, it searches for the type of class of the manufacturer parameter. The type of automatic assembly is then carried out for all the manufacturer's parameters. Your attention, please., If none of the containers is entirely of the bean manufacturer parameter type, A fatal error.

25 、 Spring How to use annotations to configure Bean? What are the relevant notes? ?
Answer: First, add the following configuration to the configuration file :


And it can be used @ Component 、 @ Controller 、 @ Service 、 @Repository Annotation to annotate the need by Spring IoC Class in which the container houses the object . There is no essential difference between these notes, It's just that @ Controller Generally used for controllers, @ Service Generally used in business logic classes, @Repository Generally used for storage (Like our DAOC Category of Implementation), Normal Class @ComponentPark.

26 、 Spring What types of transaction management are supported? Which method do you use in your project? ?
Answer: Spring Support for programmatic transaction management and reporting management. Many people choose the reporting management of transactions, Because it is less associated with the application , More in line with the concept of light container. The reporting management of transactions is better than the programmatic management of transactions, Although it is less flexible than programmatic transaction management , Because scheduled transactions allow you to control your business by Code .

The transactions are divided into global and local transactions . Global transactions are managed by the application server, required under-jacent JTASoutien (For example: WebLogic 、WildFlyWattendez.). Local transactions are linked to the persistence scheme adopted under - jacent, For example, using JDBC During persistence, To be usedConnection Object to manipulate the transaction; And adopt Hibernate During persistence, To use Session Object to manipulate the transaction .

Spring A transaction manager is provided as follows: .

DataSourceTransactionManagerInjectionDataSource
HibernateTransactionManagerInjectionSessionFactory
JdoTransactionManagerJDOServices management
JtaTransactionManagerUse JTAS Management Services

The parent interface of these transactions is PlatformTransactionManager.Spring The transaction management mechanism is a typical policy model ,PlatformTransactionManager Managing interface for delegates' transactions , The interface defines three methods , The interface does not know how to manage underlying transactions , But its implementation class must provide getTransaction(Methods (Open the transaction) (commit(Methods (Submit a transaction) 、 rollback(Methods (Rollback operations) Polymorphic implementation of , This makes it possible to represent different strategies for managing transactions with different implementation classes. Use JTA When the overall transaction policy , Requires support from the underlying application server , And the different JTA application servers There may be differences in detail in global transactions , Therefore, the actual configuration of the global transaction manager may require the use JtaTransactionManagerUnder - class,For example :: WebLogicJtaTransactionManager (OracleDeWebLogicFourni by the server) (UowJtaTransactionManager (IBMDeWebSphereFourni by the server) Wait..

The management of programming transactions is as follows: .






jdbc.properties




$ {db.driver}


$ {db.url}


$ {db.username}


$ {db.password}




















package com.hzy.dao.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import com.hzy.dao.EmpDao ;
import com.hzy.entity.Emp;
@Repository
public class EmpDaoImpl implementations EmpDao {
@Autowired
private JdbcTemplate jdbcTemplate ;
@Override
public boolean save (Emp emp) {
String sql = "insert into emp values (?,?,?)";
return jdbcTemplate.update (sql, emp.getId (), emp.getName (), emp.getBirthday ()) == 1 ;
}
}
package com.hzy.biz.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult ;
import org.springframework.transaction.support.TransactionTemplate ;
import com.hzy.biz.EmpService;
import com.hzy.dao.EmpDao ;
import com.hzy.entity.Emp;
@Service
public class EmpServiceImpl implementations EmpService {
@Autowired
private TransactionTemplate txTemplate ;
@Autowired
private EmpDao empDao ;
@Override
public void addEmp (final Emp emp) {
txTemplate.execute (new TransactionCallbackWithoutResult () {
@Override
protected void doInTransactionWithoutResult (TransactionStatus txStatus) {
empDao.save (emp) ;
}
});
}
}

The reporting transactions are presented below. , By SpringIntegrationHibernate 3 For example, including complete DAO and Logical Code of enterprise .
















































hibernate.dialect = org.hibernate.dialect.MySQL5Dialect











package com.hzy.dao;
import java.io.Serializable ;
import java.util.List;
import com.hzy.comm.QueryBean;
import com.hzy.comm.QueryResult;
/ **
* Data access object interface (Capsulation by CRUDF operation)
*
* @param  Type of entity
* @param  Type of entity identification field
* /
public BaseDao interface  {
/ **
* New
* @param entity Purpose of the commercial entity
* @return Add the identity of the entity object successfully returned
* /
public K save (E entity) ;
/ **
* Remove
* @param entity Purpose of the commercial entity
* /
public void delete (E entity) ;
/ **
* According to IDSuppress
* @param id Identification of the object of the commercial entity
* @return Suppressed successfully returned otherwise, return to false
* /
public boolean deleteById (K id) ;
/ **
* Edit
* @param entity Purpose of the commercial entity
* @return Modification successfully returned true Otherwise, return to false
* /
public void update (E entity) ;
/ **
* According to ID Find objects of commercial entity
* @param id Identification of the object of the commercial entity
* @return Object of the commercial entity or null
* /
public E findById (K id) ;
/ **
* According to ID Find objects of commercial entity
* @param id Identification of the object of the commercial entity
* @param lazy Use deferred loading
* @return Purpose of the commercial entity
* /
public E findById (K id, boolean lazy) ;
/ **
* Find all objects of the commercial entity
* @return List container containing all the objects of the commercial entity
* /
public List findAll () ;
/ **
* Search for commercial entity objects per page
* @param page Number of pages
* @param size Page size
* @return Object of result of the request
* /
QueryResult audience findByPage (int page, int size) ;
/ **
* Search for commercial entity objects per page
* @param queryBean Purpose of the request criteria
* @param page Number of pages
* @param size Page size
* @return Object of result of the request
* /
QueryResult audience findByPage (QueryBean queryBean, int page, int size) ;
}
package com.hzy.dao;
import java.io.Serializable ;
import java.util.List;
import com.hzy.comm.QueryBean;
import com.hzy.comm.QueryResult;
/ **
* BaseDao Default adapter for
*
* @param  Type of entity
* @param  Type of entity identification field
* /
public abstract class BaseDaoAdapter implementations
BaseDao {
@Override
public K save (E entity) {
return null;
}
@Override
public void delete (E entity) {
}
@Override
public boolean deleteById (K id) {
E entity = findById (id) ;
if (entity != null) {
delete (entity) ;
return true ;
}
return false ;
}
@Override
public void update (E entity) {
}
@Override
public E findById (K id) {
return null;
}
@Override
public E findById (K id, boolean lazy) {
return null;
}
@Override
public List findAll () {
return null;
}
@Override
QueryResult audience findByPage (int page, int size) {
return null;
}
@Override
QueryResult audience findByPage (QueryBean queryBean, int page, int size) {
return null;
}
}
package com.hzy.dao;
import java.io.Serializable ;
import java.lang.reflect.ParameterizedType ;
import java.util.ArrayList ;
import java.util.Collections;
import java.util.List;
import org.hibernate.Query ;
import org.hibernate.Session;
import org.hibernate.SessionFactory ;
import org.springframework.beans.factory.annotation.Autowired;
import com.hzy.comm.HQLQueryBean ;
import com.hzy.comm.QueryBean;
import com.hzy.comm.QueryResult;
/ **
* Based on HibernateDeBaseDao Implementation category
*
* @param  Type of entity
* @param  Type of primary key
* /
@SuppressWarnings (value = {"unchecked"})
public abstract class BaseDaoHibernateImpl extends BaseDaoAdapter {
@Autowired
protected SessionFactory sessionFactory ;
private Class entityClass; // Class object of the commercial entity
private String entityName; // Name of the commercial entity
public BaseDaoHibernateImpl () {
ParameterizedType pt = (ParameterizedType) this.getClass ().getGenericSuperclass () ;
entityClass = (Class) pt.getActualTypeArguments () [0] ;
entityName = entityClass.getSimpleName () ;
}
@Override
public K save (E entity) {
return (K) sessionFactory.getCurrentSession () .save (entity) ;
}
@Override
public void delete (E entity) {
sessionFactory.getCurrentSession () .delete (entity) ;
}
@Override
public void update (E entity) {
sessionFactory.getCurrentSession ().update (entity) ;
}
@Override
public E findById (K id) {
return findById (id, false) ;
}
@Override
public E findById (K id, boolean lazy) {
Session session = sessionFactory.getCurrentSession () ;
return (E) (lazy? session.load (entityClass, id): session.get (entityClass, id)) ;
}
@Override
public List findAll () {
return sessionFactory.getCurrentSession ().createCriteria (entityClass).list () ;
}
@Override
QueryResult audience findByPage (int page, int size) {
return new QueryResult(
findByHQLAndPage ("from" + entityName, page, size),
getCountByHQL ("select count (*) from" + entityName)
);
}
@Override
QueryResult audience findByPage (QueryBean queryBean, int page, int size) {
if (queryBean instanceof HQLQueryBean) {
HQLQueryBean hqlQueryBean = (HQLQueryBean) queryBean ;
return new QueryResult(
findByHQLAndPage (hqlQueryBean.getQueryString (), page, size, hqlQueryBean.getParameters ()),
getCountByHQL (hqlQueryBean.getCountString (), hqlQueryBean.getParameters ())
);
}
return null;
}
/ **
* According to HQL And a list of variable parameters to be interviewed
* @param hql Based onHQL Application instruction for
* @param params List of variable parameters
* @return List container or empty list container containing the results of the request
* /
protected List findByHQL (String hql, Object... parameters) {
return this.findByHQL (hql, getParamList (params)) ;
}
/ **
* According to HQL And the list of parameters to be questioned
* @param hql Based onHQL Application instruction for
* @param params List of request parameters
* @return List container or empty list container containing the results of the request
* /
protected List findByHQL (String hql, List parameters) {
List list = createQuery (hql, params) .list () ;
return list != null & & list.size ()> 0 ? list: Collections.EMPTY_LIST ;
}
/ **
* According to HQL Application filed with list of parameters
* @param hql Based onHQL Application instruction for
* @page Number of pages
* @ size Page size
* @param params List of variable parameters
* @return List container or empty list container containing the results of the request
* /
protected List findByHQLAndPage (String hql, int page, int size, Object... parameters) {
return this.findByHQLAndPage (hql, page, size, getParamList (params)) ;
}
/ **
* According to HQL Application filed with list of parameters
* @param hql Based onHQL Application instruction for
* @page Number of pages
* @ size Page size
* @param params List of request parameters
* @return List container or empty list container containing the results of the request
* /
protected List findByHQLAndPage (String hql, int page, int size, List parameters) {
List list = createQuery (hql, params)
.setFirstResult ((page - 1) * size)
.setMaxResults (size)
.list () ;
return list != null & & list.size ()> 0 ? list: Collections.EMPTY_LIST ;
}
/ **
* Number of records meeting the query criteria
* @param hql Based onHQL Application instruction for
* @param params List of variable parameters
* @return Total number of registrations meeting the request criteria
* /
protected long getCountByHQL (String hql, Object... parameters) {
return this.getCountByHQL (hql, getParamList (params)) ;
}
/ **
* Number of records meeting the query criteria
* @param hql Based onHQL Application instruction for
* @param params Param list container
* @return Total number of registrations meeting the request criteria
* /
protected long getCountByHQL (String hql, List parameters) {
return (Long) createQuery (hql, parameters). uniqueResult () ;
}
// CreationHibernateObject of the request (Query)
private Query createQuery (String hql, List parameters) {
Query query = sessionFactory.getCurrentSession ().createQuery (hql) ;
for (int i = 0; i  getParamList (Object... parameters) {
List paramList = new ArrayList <> () ;
if (params != null) {
for (int i = 0; i package com.hzy.comm ;
import java.util.List;
/ **
* Interface for request criteria
*
* /
public QueryBean interface {
/ **
* Add a sorting field
* @param fieldName Sorting fields
* @param ascending or descending
* @return Request criteria itself (Easy cascading programming)
* /
public QueryBean addOrder (String fieldName, boolean asc) ;
/ **
* Add a sorting field
* @param available Add this sorting field
* @param fieldName Sorting fields
* @param ascending or descending
* @return Request criteria itself (Easy cascading programming)
* /
public QueryBean addOrder (available boolean, String fieldName, boolean asc) ;
/ **
* Add request criteria
* @param condition Conditions
* @param params Replace a parameter with a parameter substituent in a condition
* @return Request criteria itself (Easy cascading programming)
* /
public QueryBean addCondition (String condition, Object... parameters) ;
/ **
* Add request criteria
* @param available This condition must be added?
* @param condition Conditions
* @param params Replace a parameter with a parameter substituent in a condition
* @return Request criteria itself (Easy cascading programming)
* /
public QueryBean addCondition (available boolean, String condition, Object... parameters) ;
/ **
* Obtain the request instruction
* @return Application instruction
* /
public String getQueryString () ;
/ **
* Obtain the request instruction for the number of request records
* @return Application instruction for the number of request records
* /
public String getCountString () ;
/ **
* Obtain request parameters
* @return List content for query parameters
* /
public List getParameters () ;
}

package com.hzy.comm ;
import java.util.List;
/ **
* Results of the request
*
* @param  Generic parameters
* /
public class QueryResult {
private List result; // List container containing the results of the request
private long totalRecords; // Total number of recordings interviewed
/ **
* Manufacturer
* /
public QueryResult () {
}
/ **
* Manufacturer
* @param result List container containing the results of the request
* @param totalRecords Total number of recordings interviewed
* /
public QueryResult (List result, long totalRecords) {
this.result = result ;
this.totalRecords = totalRecords ;
}
public List getResult () {
return result ;
}
public void setResult (List result) {
this.result = result ;
}
long public getTotalRecords () {
total returnRecords;
}
public void setTotalRecords (long totalRecords) {
this.totalRecords = totalRecords ;
}
}
package com.hzy.dao;
import com.hzy.comm.QueryResult;
import com.hzy.entity.Dept;
/ **
* Interface subject to access to Ministry data
*
* /
public interface DeptDao extends BaseDao {
/ **
* Page Query top Department
* @param page Number of pages
* @param size Page size
* @return Object of result of the request
* /
QueryResult audience findTopDeptByPage (int page, int size) ;
}
package com.hzy.dao.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.hzy.comm.QueryResult;
import com.hzy.dao.BaseDaoHibernateImpl;
import com.hzy.dao.DeptDao ;
import com.hzy.entity.Dept;
@Repository
public class DeptDaoImpl extends BaseDaoHibernateImpl DeptDao implementations {
private static final String HQL_FIND_TOP_DEPT = "from Dept as d where d.superiorDept is null" ;
@Override
QueryResult audience findTopDeptByPage (int page, int size) {
List list = findByHQLAndPage (HQL_FIND_TOP_DEPT, page, size) ;
long totalRecords = getCountByHQL ("select count (*)" + HQL_FIND_TOP_DEPT) ;
return new QueryResult <> (list, totalRecords) ;
}
}
package com.hzy.comm ;
import java.util.List;
/ **
* Pager
*
* @param  Types of data objects loaded
* /
public class PageBean {
private static final int DEFAUL_INIT_PAGE = 1 ;
private static final int DEFAULT_PAGE_SIZE = 10 ;
private static final int DEFAULT_PAGE_COUNT = 5 ;
private List data; // Pagination data
private PageRange pageRange; // Number of pages
private int totalPage; // Total number of pages
private int size; // Page size
private int currentPage; // Current page
private int pageCount; // Number of pages
/ **
* Manufacturer
* @param currentPage Current page
* @param size Page size
* @param pageCount Number of pages
* /
public PageBean (int currentPage, int size, int pageCount) {
this.currentPage = currentPage> 0 ? currentPage: 1 ;
this.size = size> 0 ? size: DEFAULT_PAGE_SIZE ;
this.pageCount = pageCount> 0 ? size: DEFAULT_PAGE_COUNT ;
}
/ **
* Manufacturer
* @param currentPage Current page
* @param size Page size
* /
public PageBean (int currentPage, int size) {
this (currentPage, size, DEFAULT_PAGE_COUNT) ;
}
/ **
* Manufacturer
* @param currentPage Current page
* /
public PageBean (int currentPage) {
this (currentPage, DEFAULT_PAGE_SIZE, DEFAULT_PAGE_COUNT) ;
}
/ **
* Manufacturer
* /
public PageBean () {
this (DEFAUL_INIT_PAGE, DEFAULT_PAGE_SIZE, DEFAULT_PAGE_COUNT) ;
}
public List getData () {
return data ;
}
public int getStartPage () {
return pageRange != null ? pageRange.getStartPage (): 1 ;
}
public int getEndPage () {
return pageRange != null ? pageRange.getEndPage (): 1 ;
}
long public getTotalPage () {
return totalPage ;
}
public int getSize () {
return size .
}
public int getCurrentPage () {
return currentPage ;
}
/ **
* Convert the results of the query to paged data
* @param queryResult Subject of the request's result
* /
public void transferQueryResult (QueryResult queryResult) {
long totalRecords = queryResult.getTotalRecords () ;
data = queryResult.getResult () ;
totalPage = (int) ((totalRecords + size - 1) / size) ;
totalPage = totalPage> = 0 ? totalPage: Integer.MAX_VALUE ;
this.pageRange = new PageRange (pageCount, currentPage, totalPage) ;
}
}
package com.hzy.comm ;
/ **
* Number of pages
*
* /
public class PageRange {
private int startPage; // Starting page
private int endPage; // End of page
/ **
* Manufacturer
* @param pageCount Total number of pages displayed
* @param currentPage Current page
* @param totalPage Total number of pages
* /
public PageRange (int pageCount, int currentPage, int totalPage) {
startPage = currentPage - (pageCount - 1) / 2 ;
endPage = currentPage + pageCount / 2 ;
if (startPage <1) {
startPage = 1 ;
endPage = totalPage> pageCount ? pageCount: totalPage ;
}
if (endPage> totalPage) {
endPage = totalPage ;
startPage = (endPage - pageCount> 0) ? endPage - pageCount + 1: 1 ;
}
}
/ **
* Get the starting page number
* @return Starting page
* /
public int getStartPage () {
return startPage ;
}
/ **
* Get the end page number
* @return End page
* /
public int getEndPage () {
return endPage ;
}
}
package com.hzy.biz ;
import com.hzy.comm.PageBean;
import com.hzy.entity.Dept;
/ **
* Operational logical interface of the Ministry
*
* /
public DeptService interface {
/ **
* Create a new Department
* @param department Purpose of the Ministry
* @return Create a successful return Otherwise, return to false
* /
public boolean createNewDepartment (Department Department) ;
/ **
* Delete the designated ministry
* @param id Ministry number to be deleted
* @return Suppressed successfully returned otherwise, return to false
* /
public boolean deleteDepartment (Integer id) ;
/ **
* Obtain high-level ministries per page
* @param page Number of pages
* @param size Page size
* @return Pagination object for the Department object
* /
public PageBean getTopDeptByPage (int page, int size) ;
}
package com.hzy.biz.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hzy.biz.DeptService;
import com.hzy.comm.PageBean;
import com.hzy.comm.QueryResult;
import com.hzy.dao.DeptDao ;
import com.hzy.entity.Dept;
@Service
@Transactional // Comments on reporting transactions
public class DeptServiceImpl implementations DeptService {
@Autowired
private DeptDao deptDao ;
@Override
public boolean createNewDepartment (Department Department) {
return deptDao.save (department) != null ;
}
@Override
public boolean deleteDepartment (Integer id) {
return deptDao.deleteById (id) ;
}
@Override
public PageBean getTopDeptByPage (int page, int size) {
QueryResult queryResult = deptDao.findTopDeptByPage (page, size) ;
PageBean pageBean = new PageBean <> (page, size) ;
pageBean.transferQueryResult (queryResult) ;
return pageBean ;
}
}

27 、 How to make WebConfiguration in the SpringDeIoCConteneur project ?
Answer: If necessaryWebUtilized in the SpringDeIoCConteneur project, It could be inWebProfil of the projectweb.xml Configure as follows:


contextConfigLocation
classpath: applicationContext.xml



org.springframework.web.context.ContextLoaderListener


28 、 How to make WebConfiguration in the Spring MVC project ?
Answer: To be usedSpring MVCBesoin deWeb Configure its frontal controller in the profile of the DispatcherServlet project, As follows:



example

org.springframework.web.servlet.DispatcherServlet

1


example
* .html


** Description: ** Used in the configuration above * .html Suffixe Mapping for, This is not possible. URL Deduct which server-side technology is used. On the other hand, you can deceive the search engines, Because the search engines are not looking for dynamic pages, This approach is called pseudo-static .

29 、 Spring MVC How it works? ?

SpringMVCPprocess

  • The user sends a request to the Front Controller DispatcherServlet.

  • DispatchServlet Request call receivedHandlerMappingProcessor mapper.

  • The processor mapper has found the specific processor (Can be based on xmlConfiguration 、 Notation for research), Generate processor objects and processor interceptors (If yes, generate) Back to DispatcherServlet.

  • DispatchServletCallHandlerAdapter Processor adapter.

  • HandlerAdapter Call a specific adaptation processor (Controller, also called Rear Controller).

  • ControllerExecution completed by ModelAndView.

  • HandlerAdapterOui.controlResults of the implementationModelAndViewRetour inDispatcherServlet.

  • DispatchServletOui.ModelAndViewTransmis àViewResloverSee the analyzer.

  • ViewResloverR sends details after analysisView.

  • DispatchServletSelonViewMake a rendering view (Fill the model data in the view).

  • DispatchServletRespond to users.

Description of the component :

The following are generally implemented using a framework :

  • DispatchServlet: As a Front Controller, Process Control Center, Control the Execution of Other Components, Uniform Distribution, Reduce Coupling Between Components, Increase Extensibility of Each Component .

  • HandlerMapping: Different mapping methods are implemented by the extended processor mapper, For example: Profile par, Implementation interface mode, Annotation mode, etc..

  • HandlAdapter: Via an extended processor adapter, Support for more types of processors.

  • ViewResolver: By expanding the view analyzer, Taking charge of more types of vision resolution, For example: jsp 、 vre 、 、 、 、 、 、 admeclAttendez..

Components :
1Frontal controllerDispatcherServlet (No need to be developed by the Engineer), Furnished by frame
Action: Reception of requests, Results of the response, The equivalent of a transponder, CPU. It's good.dispatcherServlet Reduction of coupling between other components .
User request to the Front Controller, This is the equivalent of demvcEn modec, dispatcherServletEst the Control Center for the whole process, He calls other components to process user requests, dispatcherServletReduction of coupling between components .

2Processor mapperHandlerMapping (No need to be developed by the Engineer), Furnished by frame
Action: On applicant Find Handler
HandlerMapping Search Manager at the request of the user HandlerProcessor, springmvc Different mappers are provided to implement different mapping methods, For example: Profile par, Implementation interface mode, Annotation mode, etc..

3HandlerAdapter processor adapter
Action: According to specific rules (HandlerAdapterRules required) To implement Handler
AdoptionHandlerAdapterExecution of the processor, It is the application of the adapter mode, More types of processors can be executed with extension adapters.

4Handler processor (Must be developed by the Engineer)
Warning!: CompilationHandlerSelonHandlerAdapterTo do it, For the adapter to work properly Handler
Handler It is after DispatcherServlet Rear Controller of the Front Controller, InDispatcherServletSous controlHandlerTreatment of specific user requests.
Because Handler Specific User Requests, Therefore, the general circumstances require the Engineer to develop according to operational needs. Handler.

5See the analyzerView resolver (No need to be developed by the Engineer), Furnished by frame
Action: Perform an analysis of view, Solve to the true view based on the name of the logical view (view)
View Resolver Responsible for producing processing resultsViewSee, View Resolver First, by the name of the logical view, the name of the physical view is analyzed, that is - to say the address of the specific page., RegenerateViewSee the object, Finally, yes.ViewRendre to display the results of the treatment to the user on a page. springmvcThe framework offers a lotViewType of view, Including :: jstlView 、fremarkerView 、 pdfViewWWattendez..
In general, model data should be displayed to the user on the page using page labels or page templates., Specific pages must be drawn up by the Engineer according to operational needs. .

6 See View (Must be developed by the Engineer ...)
ViewEst an interface, The implementation classes support different ViewType (jsp 、 freemarker 、 ...)

The specific stages of the basic architecture process are as follows::
1 The user first sends the request ——> DispatcherServlet, The Front Controller does not process the request himself. Instead, he is delegated to another Analyzer for processing, As access point unified, Global process control;
2DispatcherServlet ——> HandlerMapping, HandlerMapping The request will be mapped as follows: HandlerExecutionChain Object (Contains a Handler Processor (Page Controller) Object (Several HandlerInterceptor Interceptor) Object, Thanks to this strategic model, It is easy to add a new mapping policy ;
3DispatcherServlet ——> HandlerAdapter, HandlerAdapter The processor will be packed as an adapter, Support for several types of processors, Application of the adapter design mode, so it's easy to support many types of processors
4HandlerAdapter ——> Call of the processor function processing method, HandlerAdapter The functional processing of the real processor will be called according to the result of the adjustment, Complete processing of functions; And returns aModelAndView Object (Including model data 、 Name of logical view) ;
5ModelAndView Name of the logical view for ——> ViewResolver, ViewResolver The name of the logical view will be analyzed in detail View, Thanks to this strategic model, It is easy to replace other visual technologies
6View ——> Render, View As has happened Model Data for the rendering, HereModelIn fact, it is a Data Structure, so it is easy to support other visualization technologies;
7 Back to DispatcherServlet control, ByDispatcherServlet Return the response to the user, This process is complete .

The following two components should normally be developed:

  • Handler: Processor, that is - to - say for the rear controller control Representation.
  • View: See, The interface displayed to the user, A label language is often necessary to display the model data in a view .

30 、 How to do Spring IoC Configure the data source in the container?
Answer:
DBCPConfiguration :








C3P0Configuration :








31 、 How to configure configuration transaction improvements?
Answer:

































32 、 Choose to useSpringThe reason for the framework (Spring What are the advantages of the framework for business development? )?
Answer: The answers can be obtained from the following aspects::
- Not intrusive: Support based on POJOMode of programming for, Realization of non-compulsory requirements Spring Interface or inheritance in the framework of Spring Classes in the frame .
- IoCConteneur: IoC Container helps the application to manage objects and dependencies between them ,Dependencies between objects if a change occurs, just change the profile rather than the Code,Because amending the Code could mean rebuilding the project and a complete regression test. It's good, Programmers no longer need to write their own factory "A unique case, This is particularly true Spring The spirit of "Do not repeat the invention of the wheel".
- PDO (Tangent oriented programming): Encapsulation of all the transversal attention functions in the Section (aspect) Average, Dynamic addition of the transverse attention function to the object code by configuration, The separation between the operational logic and the services of the system is also performed. On the other hand, it's good. PDO Programmers can save a lot of work by writing their own proxy classes .
- MVC: SpringDeMVC The frame is excellent, It can be dropped in all its aspects. Struts 2Some streets., PourWeb The presentation layer offers a better solution .
- Transaction management: Spring A wide range of persistent layer technologies, and provides declarative transaction management, Transaction management without any required lines of code .
- Others: SelectSpring The reasons for the framework go far beyond ,SpringPourJava The development of the company offers a one-stop shop , You can use it in part and in full if necessary ,More importantly, You can't even feel SpringIn presence, Use a variety of great features in your Spring Offer project .

33 、 Spring IoCConfiguration of the Bean container How?
Answer:
- Based on XMLFile to configure.
- Configuration by annotation .
- Based on JavaConfiguration of the program (Spring 3+)

package com.hzy.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Person {

private String name ;
private int age ;
@Autowired
private Car car;
public Person (String name, int age) {

this.name = name ;
this.age = age ;
}
public void setCar (Car car) {

this.car = car ;
}
@Override
public String toString () {

return "Person [name =" + name + ", age =" + age + ", car =" + car + "]";
}
}
package com.hzy.bean;
import org.springframework.stereotype.Component;
@Component
public class Car {

private String brand ;
private int maxSpeed ;
public Car (String brand, int maxSpeed) {

this.brand = brand ;
this.maxSpeed = maxSpeed ;
}
@Override
public String toString () {

return "Car [brand =" + brand + ", maxSpeed =" + maxSpeed + "]" ;
}
}
package com.hzy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.hzy.bean.Car;
import com.hzy.bean.Person;
@Configuration
public class AppConfig {

@Bean
public Car () {

return new Car ("Benz", 320) ;
}
@Bean
public Person person () {

return new Person ("hzy", 34) ;
}
}
package com.hzy.test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotationConfigApplicationContext;
import com.hzy.bean.Person;
import com.hzy.config.AppConfig;
class Test {

public static void main (String [] args) {

// TWR (Java 7+)
try (ConfigurableApplicationContext factory = new AnnotationConfigApplicationContext (AppConfig.class)) {

Person person = factory.getBean (Person.class) ;
System.out.println (person) ;
}
}
}

34 、 PresentationSpringIn the contextThe life cycle of ?
Answer:
1 Spring IoC Container found about Bean Define and installer Bean.
2 Spring IoCPaire of containersBeanE give a dependent injection.
3 SiBeanIt's done.BeanNameAwareInterface, so put thisBeanDeidTransmis tosetBeanNameMethods.
4 SiBeanC is done.BeanFactoryAwareInterface, SoBeanFactoryObject passed tosetBeanFactoryMethods.
5 SiBean It's done. BeanPostProcessorInterface, Called postProcessBeforeInitializationMethods.
6 SiBeanC is done.InitializingBeanInterface, Called afterPropertySetMethods.
7 If there is and BeanAssociativeBeanPostProcessorsObject, Of these objects, postProcessAfterInitializationMethod called.
8 When Bean destroys For example, SiBeanC is done. DisposableBeanInterface, Called destroyMethods.

35 、 How to inject collection attributes according to the injection ?
Answer: Can be defined in BeanProperty, Adoption / / / Inject the list separately 、 All 、 (The values of the card and the key are card attributes for a string .

36 、 Spring What are the limits of automatic assembly in?
Answer:
- If the manufacturer's injection is used or setterInjection, the dependencies of the automatic assembly will be overwritten .
- Value of the type of basic data 、 "Literate chain 、 class literatures cannot be injected using automatic assembly .
- Preference is given to the use of explicit assemblies for a more precise injection of dependence rather than to the use of automatic assemblies.

37 、 InWeb How to get in the SpringDeIoCConteneur project ?
Answer:

WebApplicationContext ctx =
WebApplicationContextUtils.getWebApplicationContext (servletContext) ;

38 、 What questions major websites should - they examine architecturally? ?
Answer:

  • Stratification: Stratification is one of the most common ways to deal with any complex system , Divide the system laterally into several levels , Only one responsibility per level ,It is then used to form a complete and complex system thanks to the infrastructure and services provided by the layer below the upper layer and the transfer of the layer above the lower layer. Reference model for the interconnection of open systems in computer networks (OSI / RM) And InternetDeTCP / IP The models are stratified ,Large website software systems can also be divided into persistent layers using the concept of layers (Providing data storage and access services) 、 Business level (Managing business logic, The most central part of the system) And the presentation layers (System interaction 、 View). It should be emphasized that: (1) Stratification is a logical division ,Different functional modules can be physically deployed on the same device or on different devices, This allows more IT resources to be used to meet simultaneous user access ;(2) There must be a clear limit between the layers , So that stratification makes sense , Is more conducive to software development and maintenance .
  • Divide: Segmentation is a longitudinal segmentation of the software . We can divide the different functions and services of a large website, a functional module that forms high cohesion and low coupling (Unit). Coarse segmentation can be done at the start of design, Divide the website into functional modules, The fine grain segmentation of each module can be done later. , This aspect is useful for software development and maintenance. On the other hand, it facilitates distributed deployment, Extension of the simultaneous capacity and functionality of the website .
  • Distributed: In addition to the above, Static Site Resources (JavaScript 、 CSS 、 Photos, etc.) You can also use an independent distributed deployment and an independent domain name. This reduces the load pressure on the application server, also allows the browser to load assets more quickly . Access to data should also be distributed, traditional commercial level relational database products mainly support distributed deployment, and the new NoSQL Products are almost distributed. Of course., Distributed technology is also used for back-up business processing - website plan. , For example, the construction of a query index (Data analysis, etc., These companies are huge in IT, Can be usedHadoopEtMapReduce Computer frame distributed to process .
  • Cluster: Cluster allows more servers to offer the same service, Can better compete .
  • Hide: Caching is a technology that exchanges space for time. , Place the data as close as possible to the calculation . The use of cache is the first law of site optimization. What we usually say CDN 、 Reverse agent (Hotspot data is the use of cache technology .
  • Asynchronous: Asynchronous is another important means of decoupling between software entities . Asynchronous architecture is a typical producer-consumer model , There is no direct appeal relationship between the two , As long as the data structure remains unchanged , The functional implementations of each other can be freely modified without mutual influence , It is very good for the expansion of the site . The use of asynchronous processing also improves the availability of the system, Accelerating the response of the site (AvecAjax Loading data is an asynchronous technique), At the same time, it can also play a peak cut-off role (Facing high instant competition)."Anything that can be postponed must be postponed. "Is the second website optimization law, and asynchronous is an important means of implementing the second website optimization law .
  • Redundancy: All servers must provide redundant servers to ensure that the site works properly when one or more servers stop, also offers the possibility of disaster recovery . Redundancy is an important guarantee of high availability of the website .

39 、 What are the frontal optimization techniques that you used?
Answer:
1 Optimization of access to the browser :
- ReductionHTTPNumber of requests: MergeCSS / MergeJavaScript / Merge images (CSS Sprite)
- Use the Navigator cache: Via the HTTP parameters In the response headCache-ControlEExpiresProperties, Yes
.CSS 、 JavaScript 、 Images, etc., are cached in the Navigator, When these static resources must be updated, Can be updated HTML References in the file to allow the browser to request new assets again
- Activate compression
- CSSAvant, JavaScriptPostposition
- DecreaseCookieTransmission
2 CDNAcceleration: CDN (Content Distribute Network) The nature of the cache , Hide the data at the location closest to the user ,CDN Generally deployed in the rooms of network operators , Not only increases the response speed , Also reduces the pressure on the application server. Of course., CDN The resources cached are generally static .
3 Reverse agent: The reverse Proxy is equivalent to a facade of the application server, Can protect site security, Load balancing can also be achieved, The most important, of course, is that it hides resources Hotspot to which users have access. , You can return something directly from the reverse Proxy to the user's browser .

40 、 What application server optimization techniques have you used? ?
Answer:
1 Distributed cache: The essence of the cache is the hash table in memory, If you design a high quality hash function, In theory, the asymptotic complexity of the reading and writing time of the hash tables is O (1 ). The cache is mainly used to store high reading / writing ratios (recorded) Variables , This allows the application to read the data in the cache first , If there is none or if the data is out of date, access the database or file system. , And write the data in the cache according to the proposed rules . Access to website data is also in accordance with Law 28 (ParetoDistribution, Distribution of the power law),That is to say: 80% Visits of 20% On the data of, If you could 20% The data is cached , System performance will improve considerably. Of course., The following problems must be resolved when using the cache:
- Data frequently modified ;
- Inconsistent data and dirty reading;
- Hide the avalanche (Can be resolved using a cluster of distributed cache servers, memcached Is a widely used solution) ;
- Preheating of the cache ;
- Penetration of the cache (Missing data for persistent malicious requests).
2 Asynchronous operation: You can use the message queue to asynchronize calls, Stock event messages generated by a short period of high competition in a message queue by asynchronous treatment, To cut peaks . E-commerce site during promotion, User control requests can be queued for messages. This can withstand the impact of a large number of competing order requests on the system and the database. data. For now, most e-commerce sites are not even promoting, Control systems use message queues .
3 Use of clusters.
4 Optimization of the Code :
- Multithreading: Based on JavaDeWeb Development essentially responds to competing demands from users through Multithreading , Solve wire safety issues in programming using Multi-wire technology , The main considerations are as follows:: A. Designing an object as a stateless person (This is in contradiction with object-oriented programming , Considered a bad design in an object-oriented world), This way, there is no problem of inconsistency in the condition of the object during simultaneous access. Creation of objects within a method , So that the object is created by a thread entering the method , There is no problem with several Threads accessing the same object. UsingThreadLocal It is also good to link objects to wires , This has already been discussed above. .C. A reasonable locking mechanism should be used when simultaneously accessing resources. .
- No - blockingI / O: Use of a single wire and not - blocking I / OEst currently recognized as an application model which can make the most of the server's performance than Multithreading,Based on Node.js The server is built this way. JavaInJDK 1.4 Was introduced NIO (Non-blocking I / O),InServlet 3 Asynchronous has been introduced in the ServletThe concept of, These are non-blocking on the I / O server side provides the necessary basis .
- Reuse of resources: There are two main ways to reuse resources, The first is a unique case. , Second, the pool of objects, Pool of connection to the database that we use 、 Threads pools are techniques for pooling objects, It is a typical strategy of exchanging space against time., On the other hand, the reuse of resources is also achieved. , This avoids the overhead costs of creating and releasing unnecessary resources. .

41 、 What is - what XSSAttaque? What is - what SQLAttack by injection? What is - what CSRFA Attack ?
Answer:
- XSS (Cross Site Script,Inter-site script attack) Is an attack that injects malware into a web page to run malware in the user's browser while the user browsers on the web page. There are two forms of attack inter-site script: Reflex attack (Incouraging the user to click on one link to an integrated malware to reach the attack target,Many attackers currently use the 、 Weibo Forum publishes malware on it.) And persistent attacks (Submit a malware to the database of the attacked website,When the user is browsing a web page,Malicious script loaded with the database at page execution,QQ Previous versions of the mailbox have been used as a platform for inter-site persistent script attacks. XSS This is not new. , But the attack technique is being renovated, PreventionXSSIL there are two main aspects: disinfection (escape dangerous characters) ETHttpOnly (PreventionXSS Vol by a CookieData striker).
- SQLL injection attack is the most common form of injection attack (In addition to injection attack (Struts 2 High risk vulnerability of OGNL Implementation OSAttack by injection)),When the server uses the query parameters to build SQLDeclaration,MaliciousSQL Integrated into SQLTransfert in the execution of the database. SQL An injection attack requires knowledge of the structure of the database,There are several ways for an attacker to get a table structure: (1) If you build a website using an Open Source system,The structure of the database is also public (Currently, there are many ready-to-use systems that can create forums directly., Electronic Commerce Website, Although practical and rapid, the risk must be carefully assessed.);(2) Echo error (If the server error message is displayed directly on the page,An attacker can launch a page error with illegal parameters to understand the structure of the database with error information,WebThe application must have a user-friendly error page,On the one hand, the principle of the smallest surprise,On the one hand, error echo messages that may present a danger to the system are hidden);(3) Blind injection.PreventionSQL Injection attacks can also be sterilized,Validation of demand parameters by regular expressions,In addition,Setting is also a good way,It's mean. SQLS will be considered as SQLThe parameter for is executed instead of the command,JDBCDansPreparedStatement Is an instruction object that supports the connection of parameters,Better performance and securityStatement.
- CSRFAttack (Cross Site Request Forgery). It is an attacker who requests, Illegal operations as a legitimate user (Like transfer or display)..PreventionCSRFThe main means of identifying the applicant, There are mainly the following means: (1) Adding a token to the form (token); (2) Verification code; (3) Check in the head of the request Referer (As we mentioned earlier, image theft links are also used in this way.Tokens and validations are consumable once, so in principle, but the Verification Code is a bad user experience, Do not easily use verification codes when not necessary.Many websites currently require a verification code if they submit a form more than once in a short time without success., This gives better user experience.

** Supplement: ** The construction of the firewall is Web Important guarantee of security, ModSecurityOpen SourceWeb The best in the firewall . The construction of a corporate firewall should have a firewall on two levels ,Web The server and certain application servers can be installed between two levels of DMZ firewall, And the data and resource server should be behind the secondary firewall .

42. What is a domain model? Anemic model (anaemic domain model) And congestion model (rich domain model) What is the difference??
Answer: A domain model is a conceptual class in a domain or a visual representation of an object in the real world, Also called conceptual model or analytical object model ,It focuses on the analysis of the problem areas themselves,Discover the key concepts of the field of activity,And establish relationships between the concepts of the field of activity. The anemia model refers only to the domain objects used setterEgetterMethods (POJO), All the business logic is not contained in the domain object, but placed at the level of the business logic. Someone has subdivided our anemia model into a blood loss model. (Lobjects have no operational logic) And models of anemia (Labor objects have a small business logic), We do not make a distinction here. . The congestion model places most of the operational logic and persistence in domain objects, Company logic (Activity sector) It suffices to encapsulate the business logic 、 Processing of transactions and authorizations, etc. . . The following two figures show the hierarchical architecture of the anemia and congestion models, respectively. .

Anemic model

The logic of the Organization's domain in the anemia model usually uses the transaction script template, Matching each process to an action that the user might want to do, Each action is led by a process . This is - to say during the design of the company logical interface, Each method corresponds to a user action. This model includes the following elements::
- It is a simple process model that most developers can understand (Avens to the vast majority of national developers).
- It works well with a simple data access layer that uses line or table data entries.
- evidence of transaction limits, A transaction begins at the beginning of the script, End of the script, Easy to go through the agent (Or tangent) Implement a reporting transaction.
And yet, the disadvantages of the transaction script model are also numerous, As the logical complexity of the domain increases, The complexity of the system will increase rapidly, The structure of the program will become extremely confusing . There is a good translation in the Chinese community Open Source 中M How models of the field of anemia lead - they to bad software? ab This question is explained in detail. .

43. Test-oriented Development Discussion (TDD) The Benefits and Your Understanding .
Answer: TDD Is to write the Test Code before writing the real Functional Implementation Code , Then reconfigure the Implementation Code as needed. InJUnitAutor of Kent BeckA great chef - of work 中Development focused on tests: Real combat and analysis of models (Test-Driven Development: by Example) There is a passage in a book: “The elimination of fear and uncertainty is an important reason to write test pilots ”. Because the fear of writing Code makes you think. , To avoid communication, it makes you ashamed to have comments. , It makes you restless. , EtTDD Is to Eliminate Fear 、 JeanJava An important means for developers to be more confident and more open to communication. TDD The benefits may not be - not be immediately available, but you will find out at some point. , These benefits include::
- Clearer code - Write only the required Code
- Better design
- More flexibility - Encourage programmers to cope with interface programming
- Faster feedback - I won't know until the system is online. bugThe existence of

** Supplement: ** The concept of agile software development has existed for many years, and this has partially changed the software development industry, TDD is also advocated by agile development .

TDD Can be applied on several levels ,Including unit tests (Testing the code in a class) (Integration tests (Interaction between test classes) (System tests) and system integration test (The system tested includes the components third parties used) .TDD The implementation steps are as follows:: Red (Failed of the test) - Green (Succeeding the test) - Refactoring.In serviceTDDAt the time of development, Often, you encounter situations where the object tested must depend on other sub-systems , But you want to isolate the Dependency Test Code , To ensure that the Test Code is only extended to the object or method currently tested , What you need, it's a double test. . Test duplicates can be divided into four categories::
- False double. : Past but unused objects, List of parameters generally used for filling methods
- Double stub: Always return the same default response, This may include fictitious states
- A double disguised. : Can replace the actual version available (It's even worse than the real version. )
- Simulate a double: An object that can represent a series of expected values, And can provide a predefined response
Java There are many third-party tools in the world that implement analog avatars, including: EasyMock 、 Mockito 、 Mockito 、 MockWait..


Leave a Reply

Your email address will not be published.