Interview Questions for spring, hibernate, and struts

Source: Internet
Author: User
Tags to domain

Spring, hibernate, Struts interview questions from: http://shwenwen.itpub.net/post/34911/486887

How does hibernate work and why?
Principle:
1. Read and parse the configuration file
2. Read and parse the ing information and create sessionfactory
3. Open sesssion
4. Create transaction Transation
5. Persistent operations
6. Submit the transaction
7. Disable session
8. Disable sesstionfactory

Why:
1. For JDBC access to the databaseCodeThe encapsulation greatly simplifies the tedious and repetitive code at the data access layer.
2. Hibernate is a mainstream persistence framework based on JDBC and an excellent ORM implementation. He greatly simplifies the coding of the DaO layer.
3. hibernate uses the Java reflection mechanism instead of bytecode enhancement.ProgramTo achieve transparency.
4. hibernate has excellent performance because it is a lightweight framework. The flexibility of ing is excellent. It supports various relational databases, from one-to-one to many-to-many complex relationships.

2. How does hibernate delay loading?
1. Implementation of hibernate2 delayed loading: a) object B) Collection)
2. hibernate3 provides the property's delayed Loading Function
When hibernate queries data, the data does not exist in the memory. When the program actually operates on the data, the object exists in the memory, and the loading is delayed, it saves the server memory overhead and improves the server performance.

3. How does one implement the relationship between classes in hibernate? (For example, one-to-many and many-to-many relationships)

The relationship between classes is mainly reflected in the relationship between tables. They operate on objects in a city. In our program, all tables and classes are mapped together, they are used in the configuration file named "allow-to-one", "one-to-allow", "allow-to-allow,

4. Talk about the cache mechanism of Hibernate

1. The internal cache exists in hibernate, which is also called a level-1 cache, which belongs to the application thing-level cache.

2. Secondary cache:
A) Application and Cache
B) distributed cache
Condition: the data is not modified by a third party, the data size is within the acceptable range, the data update frequency is low, the same data is frequently used by the system, non-critical data
C) third-party cache implementation

5. Hibernate query method
First: Get () and load ()
Session. Get (clazz, ID );
Session. Load (clazz, ID );
Note: differences between load () and get ()
Note that if no matching database records exist, the load () method may throw an unrecoverable exception
Exception ). If the class ing uses proxy, the load () method returns an uninitialized proxy until you call

A Method of the proxy will access the database. If you want to create an association pointing to another object in an object, you do not want

When this object is loaded from the database and the associated object is loaded at the same time, this operation method can be used. For the corresponding class

If batch-size is set for the ing relationship, this operation allows multiple objects to be loaded in batches (because the returned result is a proxy, no

Data of all objects needs to be captured from the database ).
If you are not sure whether a matched row exists, you should use the get () method, which will immediately access the database. If no corresponding row exists, null is returned.

Type 2: 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 ();
// Name Parameters
Query q = sess. createquery ("from domesticcat cat where Cat. Name =: Name ");
Q. setstring ("name", "fritz ");
// Location Parameter
Query q = sess. createquery ("from domesticcat cat where Cat. Name =? ");
Q. setstring (0, "Izi ");
// Name parameter list
Query q = sess. createquery ("from domesticcat where Cat. Name in (: nameslist )");
Q. setparameterlist ("nameslist", names );
// Query by PAGE
Query q = sess. createquery ("from domesticcat ");
Q. setfirstresult (20 );
Q. setmaxresults (10 );
List cats = Q. List ();
Category 3: 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 ();
Type 4: 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-Multiple Association instead of unidirectional one-to-Multiple Association
2. flexible use of one-to-multiple associations
3. Replace multiple-to-one instead of one-to-one
4. Configure the object cache without using the set Cache
5. Use bag for one-to-multiple sets and set for multiple-to-multiple sets
6. Use explicit polymorphism for inheritance classes
7. Fewer table fields, no more table Association, and secondary cache support

7. How does struts work? Why use struts?
Working mechanism:
Struts workflow:
When the web application starts, the initialization actionservlet will be loaded, and the actionservlet will
Read configuration information in the struts-config.xml file and store them to various configuration objects
When the actionservlet receives a customer request, it will execute the following process.
-(1) retrieve the actionmapping instance that matches the user request. If it does not exist, the system returns invalid information about the request path;
-(2) if the actionform instance does not exist, create an actionform object and save the form data submitted by the customer to the actionform object;
-(3) determine whether form verification is required based on the configuration information. If form verification is required, call the validate () method of actionform;
-(4) if the validate () method of the actionform returns or an actuiberrors object that does not contain the actionmessage, the form verification is successful;
-(5) The actionservlet determines the action to which the request is forwarded based on the actioning information contained in the actionmapping. If the corresponding action instance does not exist, create the instance first, and then call the action's execute () method;
-(6) The execute () method of action returns an actionforward object. The actionservlet is forwarding the client request to the JSP component pointed to by the actionforward object;
-(7) The actionforward object directs to the JSP component to generate a dynamic webpage and return it to the customer;

Why:
The emergence of JSP, Servlet, and JavaBean technologies makes it possible for us to build a powerful enterprise application system. However, systems built with these technologies are very messy. Therefore, we need a rule and a rule to organize these technologies. This is the framework, and Struts came into being.

Struts-based applications are composed of three types of components: controller components, model components, and view components.

8. How is the struts validate framework verified?
Configure the specific error message in the struts configuration file, and then call the validate () method in formbean.

9. Let's talk about the struts design model.
MVC mode: When a web application starts, it loads and initializes actionservler. When a user submits a form, a configured actionform object is created and filled with the corresponding data in the form. actionservler determines whether form verification is required based on the settings configured in the Struts-config.xml file, if you need to call the validate () Verification of actionform, select the action to which the request is sent. If the action does not exist, actionservlet will first create this object and then call the action's execute () method. Execute () obtains data from the actionform object, completes the business logic, returns an actionforward object, and the actionservlet then forwards the customer request to the JSP component specified by the actionforward object, the JSP specified by the actionforward object generates a dynamic webpage and returns it to the customer.

10. Why does spring work?
1. Spring MVC requests all requests to be submitted to dispatcherservlet. It will entrust other modules of the application system to handle the requests in real time.
2. The dispatcherservlet queries one or more handlermapping and finds the Controller that processes the request.
3. Submit the dispatcherservlet request to the target controller.
4. After the controller processes the business logic, a modelandview is returned.
5. The dispathcher queries one or more viewresolver view Resolvers and finds the view object specified by the modelandview object.
6. view objects are rendered and returned to the client.

Why:
{AOP allows developers to create non-behavioral concerns, known as cross-cutting concerns, and insert them into application code. With AOP, public services (such as logs, persistence, and transactions) can be decomposed into aspects and applied to domain objects without increasing the complexity of the Object Model of domain objects.
IOC allows you to create an application environment that can construct objects and then pass their collaboration objects to these objects. As the word inversion indicates, IOC is like the reversed JNDI. Instead of using a bunch of abstract factories, service locators, Singleton, and straight construction, each object is constructed with its collaborative object. Therefore, collaborator is managed by containers ).
Even an AOP framework, spring is also an IOC container. The best thing about spring is that it helps you replace objects. With Spring, you only need to add dependencies (collaboration objects) with the JavaBean attribute and configuration file ). Then, you can easily replace the collaboration object with similar interfaces as needed .}

========================================================== ======

1. httpsession session = request. getsession ()

What is the difference between http session = request. getsession (true?

Reference answer:

The function prototype of getsession (true) is: httpsession session = request. getsession (Boolean create)

If there is an httpsession that is first associated with the current request, the httpsession associated with the request is returned. If not, then:

Java code
With the current

If create = true, a new httpsession is returned,

If create = false, null is returned.

2. What is the difference between getparameter and getattribute?

Reference answer:

Attribute refers to an attribute.

Parameter refers to the content transmitted by the URL or submitted by the form.

3. Which of the following is not a value assignment?

A. + = B. <= C. <= D.> =

Reference answer:

A. It is obviously a value assignment symbol.

B. <= left shift assignment

C. No

D. >>>= right shift assignment. Fill the left blank space with 0

4. Which of the following is NOT the sub-interface of collection?

A. List B. set C. sortedset D. Map

Reference answer: d

5. Which of the following is the parent class of bufferedreader?

A. filterreader B. inputstreamreader C. pipedreader D. Reader

Reference answer: d

6. subclass A inherits the parent class B

A A = new ();

The sequence of execution of the parent class B constructor, parent class B static code block, parent class B non-static code block, subclass A constructor, subclass A static code block, and subclass A non-static code block 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 to optimize the condition query speed in the database when it is slow?
1. Create an index
2. Reduce association between tables
3. Optimize the SQL statements and try to make the SQL statements quickly locate the data. Instead of making the SQL statements perform full table queries, You Should index the tables with a large amount of data at the top.
4. Simplify the query of fields. Useless fields are not required. You have control over the returned results and try to return a small amount of data.

[2. perform multi-table queries in hibernate. Each table has several fields. That is to say, the queried result set does not have an entity class. How can this problem be solved?
Solution 1: retrieve data according to object [] data, and then group the beans by yourself
Solution 2: Write constructor to the bean of each table. For example, if Table 1 needs to find the field1 and field2 fields, one constructor is Bean (type1 filed1, type2 field2 ), then, the bean can be directly generated in hql. For details about how to use it, see the relevant documentation. I am not very clear about it.
Difference between session. Load () and session. Get ()
The session. Load/get method can read records from the database based on the specified object class and ID, and return the corresponding object. The difference is:

If no matching record is found, the get method returns NULL, and the load method throws an objectnotfoundexception.
The load method returns the proxy class instance of the object, while the get method returns the object class directly.
The load method can make full use of the existing data in the internal cache and the second-level cache, while the get method only searches for data in the internal cache. If no corresponding data is found, the second-level cache will be crossed, directly call SQL to read data.
When a session loads an object, it goes through the following process:

First, two levels of cache are maintained in hibernate. The first level of cache is maintained by the session instance, which maintains the data of all 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 session instances constructed by the current sessionfactory. In order to avoid unnecessary database access for performance consideration, session queries in the cache before calling the database query function. First, in the first-level cache, the object type and ID are used for search. If the first-level cache query hits and the data status is valid, the system returns the result directly.
Then, the session will be searched in the current "nonexists" record. If the same query condition exists in the "nonexists" record, null is returned. "Nonexists" records the query conditions of the current session instance in all previous query operations, and the query conditions of valid data cannot be queried (equivalent to a query blacklist list ). In this way, if an invalid query condition reoccurs in the session, you can quickly make a judgment to obtain the best performance.
For the load method, if no valid data is found in the internal cache, the second-level cache is queried. If the second-level cache hits, the second-level cache returns.
If no valid data is found in the cache, the database query operation (select SQL) is initiated. If no corresponding record is found after the query, the query information is recorded in "nonexists, and return null.
Create the corresponding data object based on the resultset obtained by the ing configuration and select SQL.
Include the data objects in the current Session Object Management container (level-1 cache ).
Execute the Interceptor. onload method (if there is a corresponding interceptor ).
Include data objects in the second-level cache.
If the data object implements the lifecycle interface, the onload method of the data object is called.
Returns the data object.
Primary Key Generation Mechanism of Hibernate
1) assigned
The primary key is generated by an external program and does not involve hibernate.
2) HiLo
Use hi/Lo Algorithm The implementation of the primary key generation mechanism requires additional database tables to save the Historical Status of the primary key generation.
3) seqhilo
Similar to hilo, the primary key generation mechanism implemented through the HI/lo algorithm only stores the Historical Status of the primary key in sequence, which is suitable for databases that support sequence, such as oracle.
4) Increment
The primary key increments in numerical order. The implementation mechanism of this method is to maintain a variable in the current application instance to save the current maximum value, and then add 1 as the primary key each time the primary key needs to be generated. This method may cause a problem: if multiple instances access the same database, different instances may generate the same primary key because each instance maintains its primary key status, this causes duplicate primary key exceptions. Therefore, if the same database has multiple instances to access, this method must be avoided.
5) Identity
Use the primary key generation mechanism provided by the database. Such as the primary key generation mechanism in DB2, SQL Server, and MySQL.
6) sequence
Use the sequence mechanism provided by the database to generate the primary key. For example, sequence in oralce.
7) Native
Hibernate uses identity, Hilo, and sequence as the primary key generation method based on the underlying database.
8) UUID. HEX
The algorithm generated by hibernate Based on the 128-bit unique value generates a hexadecimal value (encoded with a 32-Bit String) as the primary key.
9) UUID. String
Similar to UUID. HEX, the generated primary key is not encoded (Length: 16 ). Problems may occur in some databases (such as PostgreSQL ).
10) Foreign
Use the field of the External table as the primary key. Generally, using UUID. HEX to generate a primary key provides the best performance and database platform adaptability.
This 10 method generates OID identifiers. increment is usually used to assign the power generated by the identifiers to hibernate for processing. however, when multiple hibernate applications operate on the same database or even the same table at the same time. we recommend that you use identity based on the underlying database, but the database must support automatic growth. Of course, you can choose different methods for different databases. if you are not sure what the database you are using supports. you can choose to use native to enable hibernate to help you select identity, sequence, or Hilo.
In addition, common databases such as Oracle, DB2, SQL Server, and MySQL provide easy-to-use primary key generation mechanisms (auto-increase fields or sequence ). We can use the primary key generation method of generator-class = native in the primary key generation mechanism provided by the database.
However, it is worth noting that the primary key generation mechanism provided by some databases may not be optimal in terms of efficiency, and a large number of concurrent insert data may cause inter-Table locks. The primary key generation mechanism provided by the database is usually to save the current primary key status in an internal table (for example, for an auto-incrementing primary key, this internal table maintains the current maximum and incremental values). Then, the maximum value is read each time data is inserted, and the incremental value is added as the primary key of the new record, then, the new maximum value is updated back to the internal table. In this way, an insert operation may result in multiple internal table read/write operations in the database, along with data lock and unlock operations, this has a great impact on performance. Therefore, for systems with high requirements for concurrent insert, UUID. Hex is recommended as the primary key generation mechanism.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.