How does hibernate work and why should I use it?
Principle:
1. Read and parse the configuration file
2. Read and parse mapping information, create Sessionfactory
3. Open Sesssion
4. Create Transaction Transation
5. Persistent operation
6. Commit a transaction
7. Close session
8. Close Sesstionfactory
Why to use:
1. The code for JDBC access to the database is encapsulated, which greatly simplifies the tedious repetitive code of the data access layer.
2. Hibernate is a JDBC-based, mainstream persistence framework that is an excellent ORM implementation. He simplifies the coding of the DAO layer to a great extent
3. Hibernate uses the Java reflection mechanism rather than the bytecode enhancer to achieve transparency.
4. Hibernate performs very well because it is a lightweight framework. The flexibility of the mapping is excellent. It supports a variety of relational databases, from one-to-one to many-to-many complex relationships.
2. How does hibernate delay loading?
1. Hibernate2 Deferred load implementation: a) collection of entity object B) (Collection)
2. Hibernate3 provides properties for lazy loading functions
When hibernate is querying the data, the data does not exist in memory, and when the program actually operates on the data, the object exists in memory, and the delay is loaded, which saves the server's memory overhead and improves the performance of the server.
3. How do the relationships between classes be implemented in hibernate? (e.g. one-to-many, many-to-many relationships)
The relationship between classes and classes is mainly manifested in the relationship between tables and tables, they operate on objects, and in our program we map all the tables and classes together, through the Many-to-one, One-to-many, Many-to-many,
4. The caching mechanism of hibernate
1. Internal cache exists Hibernate is also called a first-level cache, belongs to the application of the thing-level cache
2. Level Two cache:
A) application and caching
b) Distributed cache
Conditions: Data is not modified by third parties, data size is acceptable, data update frequency is low, the same data is frequently used by the system, non-critical data
c) Implementation of third-party caches
5. How hibernate is queried
First type: Get () and load ()
Session.get (clazz, id);
Session.load (clazz, id);
Description: The difference between load () and get ()
Note that if there are no matching database records, the load () method may throw an unrecoverable exception (unrecoverable
Exception). If the class's mapping uses a proxy, the load () method returns an uninitialized proxy until you call the
A method of the agent will not access the database. If you want to create an association in an object that points to another object, and you don't want to
This is a good way to do this when you load the object from the database and load the associated object at the same time. If the corresponding class
The mapping relationship is set to batch-size, so this operation allows multiple objects to be loaded by a batch (because the returned proxy, no
You need to fetch data from all the objects in the database).
If you are unsure whether a matching row exists, you should use the Get () method, which immediately accesses the database and returns null if there are no corresponding rows.
The second type: HQL
Java code
Returns a row of records
String hql = "from Torder o where o.id =?";
Torder o = (torder) s.createquery (HQL)
. Setparameter (0, OrderId)
. Uniqueresult ();
Named parameters
Query q = Sess.createquery ("From Domesticcat cat where Cat.name =: Name");
Q.setstring ("name", "Fritz");
Position parameters
Query q = Sess.createquery ("From Domesticcat cat where cat.name =?");
Q.setstring (0, "Izi");
Named parameter list
Query q = Sess.createquery ("From Domesticcat Cat where Cat.name in (: nameslist)");
Q.setparameterlist ("NamesList", names);
Paging Query
Query q = Sess.createquery ("from Domesticcat cat");
Q.setfirstresult (20);
Q.setmaxresults (10);
List cats = Q.list ();
The Third Kind: Criteria
List cats = Sess.createcriteria (Cat.class)
. Add (Restrictions.like ("name", "fritz%"))
. Add (Restrictions.or (
Restrictions.eq ("Age", new Integer (0)),
Restrictions.isnull ("Age")
) )
. AddOrder (ORDER.ASC ("name"))
. AddOrder (Order.desc ("Age"))
. List ();
Fourth type: Native SQL
String Treesql = "" +
"Select, level from tree T" +
"Start with t.parent_id = 0" +
"Connect by prior t.id = t.parent_id";
List result = Session.createsqlquery (treesql)
. addentity ("T", Tree.class)
. Addscalar ("level", Hibernate.integer)
. List ();
6. How to optimize hibernate?
1. Use bidirectional one-to-many associations without using
2. Flexible use of unidirectional one-to-many associations
3. Do not use one-to-many substitution
4. Configure the object cache without using the collection cache
5. One-to-many collection using bag, multi-set using Set
6. Inheriting classes using explicit polymorphism
7. Table fields are less, tables associated not afraid of more, there is a level two cache backing
7. Struts working mechanism? Why use struts?
Working mechanism:
The work flow of struts:
When the web app starts, it loads the initialization actionservlet,actionservlet from
Struts-config.xml files to read configuration information and store them in various configuration objects
When Actionservlet receives a customer request, the following process is executed.
-(1) Retrieval and user request matching actionmapping instance, if not present, return the request path invalid information;
-(2) If the Actionform instance does not exist, create a Actionform object and save the form data submitted by the client to the Actionform object;
-(3) Determine if form validation is required based on configuration information. If validation is required, call Actionform's validate () method;
-(4) If Actionform's Validate () method returns or returns a Actuiberrors object that does not contain actionmessage, the form validation is successful;
-(5) Actionservlet determines which action to forward the request to, based on the mapping information contained in the actionmapping, and if the corresponding action instance does not exist, create the instance first and then invoke the Execute () method of the action;
-(6) The Execute () method of the action returns a Actionforward object that actionservlet the JSP component to which the client request is forwarded to the Actionforward object;
-(7) The Actionforward object points to the JSP component to generate a Dynamic Web page, which is returned to the customer;
Why to use:
The advent of JSP, Servlet, and JavaBean technology gives us the possibility to build powerful enterprise application systems. But the systems built with these techniques are very fanluan, so on top of that, we need a rule, a rule that organizes these technologies, and that is the framework in which struts emerges.
Struts-based applications consist of 3 types of components: Controller components, model components, view components
8. How is the validate framework of struts validated?
Configure specific error prompts in the struts configuration file, and then invoke the Validate () method in Formbean.
9. The design pattern of struts
MVC mode: Actionservler is loaded and initialized when the Web application starts. When a user submits a form, a configured Actionform object is created and populated with the corresponding data in the form. Actionservler determines whether form validation is required based on the settings configured for the Struts-config.xml file, and if it is necessary to choose which action to send the request to, after calling Actionform's validate () validation, if the action does not exist, Actionserv The let will first create the object and then call the action's execute () method. Execute () Gets the data from the Actionform object, completes the business logic, returns a Actionforward object, actionservlet the client request to the JSP component specified by the Actionforward object, The Actionforward object specifies that the JSP generates a dynamic Web page that is returned to the customer.
10. Spring working mechanism and why should it be used?
1.spring MVC requests that all requests be submitted to Dispatcherservlet, which will delegate the other modules of the application system responsible for the actual processing of the request.
2.DispatcherServlet queries one or more handlermapping to find the controller that handles the request.
3.DispatcherServlet request Submit to target Controller
4.Controller after the business logic is processed, it returns a Modelandview
5.Dispathcher querying one or more viewresolver view resolvers, locating the View object specified by the Modelandview object
6. The View object is responsible for rendering back to the client.
Why use:
{AOP allows developers to create non-behavioral concerns, called crosscutting concerns, and insert them into application code. With AOP, public services (such as logs, persistence, transactions, and so on) can be decomposed into facets and applied to domain objects without increasing the complexity of the object model of the domain object.
IOC allows you to create an application environment where objects can be constructed, and then pass their collaboration objects to those objects. As the word inversion shows, the IOC is like the reverse JNDI. Not using a bunch of abstract factories, service locators, single elements (singleton), and direct constructs (straight construction), each object is constructed with its collaboration objects. Therefore, the collaboration object (collaborator) is managed by the container.
Spring even an AOP framework, is also an IOC container. The best part of Spring is that it helps you replace objects. With Spring, you simply add dependencies (collaboration objects) with the JavaBean property and configuration file. You can then easily replace collaboration objects with similar interfaces when you need them. }
==============================================
1. HttpSession session = Request.getsession ()
What is the difference between httpsession session = Request.getsession (true)?
Reference Answer:
The function prototype for getsession (TRUE) is:: HttpSession session = request.getsession (Boolean create)
If there is a httpsession associated with the current request, then return the httpsession associated with the request, if not, then:
Java code
With the current
If Create==true, then return a new httpsession,
If create==false, then NULL is returned.
2. What is the difference between getparameter and getattribute?
Reference Answer:
Attribute refers to a property.
parameter is a parameter, something passed in by a URL or submitted by a form
3. Which of the following is not an assignment symbol?
A. + = B. <<= C. <<<= D. >>>=
Reference Answer:
A. It's obviously an assignment symbol.
B.<<= Left Shift Assignment value
C. Not
d.>>>= right Shift assignment, left empty bit filled with 0
4. Which of the following is not a collection sub-interface?
A. List B. Set c. SortedSet D. Map
Reference Answer: D
Which of the following is the parent class of 5.BufferedReader?
A. filterreader B. InputStreamReader c. pipedreader D. Reader
Reference Answer: D
6. Subclass a inherits the parent class B
A = new A ();
Then the parent Class B constructor, the parent class B static code block, the parent class B non-static code block, subclass a constructor, subclass a static code block, subclass a non-static code block execution order is?
Reference Answer: Parent class B Static code block, subclass a static code block, parent Class B constructor, parent class B non-static code block, subclass a constructor, subclass a non-static code block
1. How can I optimize conditional queries in the database when they are very slow?
1. Build an index
2. Reduce the association between tables
3. Optimize SQL, try to get SQL to locate data quickly, do not let SQL do the full table query, should go index, the data volume of the table in front
4. Simplify the query fields, no useless fields, have control over the returned results, and try to return a small amount of data
[2. In Hibernate multi-table query, each table takes several fields, that is, the query out of the result set does not have an entity class corresponding to it, how to solve this problem?
Solution One, extract the data according to object[] data, and then own the group Bean
Solution Two, the bean write constructor for each table, such as table one to find out the Field1,field2 two fields, then there is a constructor is the bean (type1 filed1,type2 field2), and then in HQL can directly generate the bean. Please look at the relevant documents for details, I am not very clear about it.
The difference between session.load () and Session.get ()
The Session.load/get method can read records from the database based on the specified entity class and ID, and returns the corresponding entity object. The difference is:
If a record that matches the condition is not found, the Get method returns NULL, and the load method throws a objectnotfoundexception.
The Load method returns an instance of the entity's proxy class, and the Get method always returns the entity class directly.
The Load method can take full advantage of the existing data in the internal cache and the level two cache, while the Get method only makes data lookups in the internal cache, and if no corresponding data is found, it passes through the level two cache and directly invokes SQL to complete the data read.
Session when you load an entity object, the process that passes:
First, a level two cache is maintained in Hibernate. The first-level cache is maintained by the session instance, which maintains data for all of the current associated entities of the session, also known as the internal cache. The second level cache exists at the sessionfactory level and is shared by all the session instances currently constructed by this sessionfactory. For performance reasons, to avoid unnecessary database access, the session will be queried in the cache before invoking the database query function. First, in the first level cache, the entity type and id are searched, and if the first level cache finds a hit and the data state is valid, it is returned directly.
The session is then searched in the current "nonexists" record, and Null is returned if the same query condition exists in the "nonexists" record. "Nonexists" records the current session instance in all previous query operations, failed to query the valid data query criteria (equivalent to a query blacklist list). As a result, if an invalid query condition recurs in the session, you can quickly make a judgment to get the best performance.
For the Load method, if no valid data is found in the internal cache, the second-level cache is queried and returned if the second-level cache hits.
If no valid data is found in the cache, the database query operation (Select SQL) is initiated, and if the query does not find the corresponding record, the information for this query is recorded in "nonexists" and returns NULL.
The corresponding data objects are created based on the resultset of the mapping configuration and select SQL.
Include its data object in the current session Entity management container (level cache).
Executes the Interceptor.onload method (if there is a corresponding interceptor).
The data objects are included in the level two cache.
If the data object implements the lifecycle interface, the OnLoad method of the data object is called.
Returns the data object.
Hibernate's primary key generation mechanism
1) assigned
The primary key is generated by an external program, without hibernate involvement.
2) Hilo
The primary key generation mechanism implemented by the HI/LO algorithm requires additional database tables to save the primary key generation history state.
3) Seqhilo
Similar to Hilo, the primary key generation mechanism implemented by the HI/LO algorithm is simply that the primary key historical state is saved in sequence and is applicable to databases that support sequence, such as Oracle.
4) Increment
The primary key is incremented in numerical order. The implementation mechanism of this method is to maintain a variable in the current application instance to hold the current maximum value, and then add 1 to the primary key each time a primary key is generated. The possible problem with this approach is that if there are multiple instances accessing the same database, the different instances may generate the same primary key as each instance maintains the primary key state, causing the primary key to repeat the exception. Therefore, this approach must be avoided if there are multiple instance accesses to the same database.
5) identity
Adopt the primary key generation mechanism provided by the database. such as DB2, SQL Server, MySQL in the primary key generation mechanism.
6) Sequence
The primary key is generated using the sequence mechanism provided by the database. such as the sequence in Oralce.
7) native
Hibernate uses identity, Hilo, sequence as the primary key generation method according to the underlying database.
8) Uuid.hex
Hibernate generates a 16 binary value based on a 128-bit unique value generation algorithm (encoded with a string of length 32) as the primary key.
9) uuid.string
Similar to Uuid.hex, only the generated primary key is not encoded (length 16). Problems (such as PostgreSQL) may occur in some databases.
) Foreign
Use the field of the external table as the primary key. In general, generating primary keys using the Uuid.hex approach provides the best performance and database platform adaptability.
This method of generating OID identifiers in 10, increment more commonly used, the power of the identifier generation to hibernate processing. But when multiple hibernate applications operate on the same database, even the same table. Identity is recommended Rely on the underlying database implementation, but the database must support autogrow, and of course choose different methods for different databases. If you are unsure of what the database you are using specifically supports in the case. You can choose to use native to help you choose Identity,sequence, or Hilo.
In addition, due to the common database, such as Oracle, DB2, SQL Server, MYSQL, etc., all provide an easy-to-use primary key generation mechanism (auto-increase field or sequence). We can use Generator-class=native's primary key generation method on the primary key generation mechanism provided by the database.
It is worth noting, however, that some databases provide a primary key generation mechanism that is not necessarily the most efficient, and that large amounts of concurrent insert data can cause interlocking between tables. The primary key generation mechanism provided by the database is often done by saving the current primary key state in an internal table (for example, the current maximum and increment is maintained in this internal table for the self-incrementing primary key), and then each time the data is inserted, the maximum value is read and the increment is used as the primary key for the new record. This new maximum value is then updated back to the internal table so that an insert operation can cause multiple table reads and writes inside the database, along with the locking unlock operation of the data, which has a significant impact on performance. Therefore, it is recommended to use Uuid.hex as the primary key generation mechanism for systems with high concurrent insert requirements.
Spring,hibernate,struts's Interview Pen test