In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what are the common interview questions in Spring,hibernate,struts". In the daily operation, I believe that many people have doubts about the common interview questions in Spring,hibernate,struts. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about "what are the common interview questions in Spring,hibernate,struts?" Next, please follow the editor to study!
How Hibernate works and why it should be used?
Principle:
1. Read and parse the configuration file
two。 Read and parse the mapping information and create a SessionFactory
3. Open Sesssion
4. Create a transaction Transation
5. Persistence operation
6. Commit transaction
7. Close Session
8. Close SesstionFactory
Why use:
1. The code of JDBC accessing database is encapsulated, which greatly simplifies the tedious and repetitive code of the data access layer.
2. Hibernate is a mainstream persistence framework based on JDBC and an excellent ORM implementation. It greatly simplifies the coding of the DAO layer.
3. Hibernate uses the Java reflection mechanism instead of a bytecode enhancer to achieve transparency.
4. Hibernate's performance is very good because it is a lightweight framework. The flexibility of mapping is excellent. It supports a variety of relational databases, from one-to-one to many-to-many complex relationships.
How does 2.Hibernate delay loading?
1. Hibernate2 delay loading implementation: a) entity objects b) collections (Collection)
2. Hibernate3 provides delayed loading of attributes.
When Hibernate is querying the data, the data does not exist in memory. When the program really operates on the data, the object exists in memory, which realizes delayed loading. It saves the memory overhead of the server, thus improving the performance of the server.
How to implement the relationship between classes in 3.Hibernate? (e. G. an one-to-many, many-to-many relationship)
The relationship between class and class is mainly reflected in the operation of the relationship between table and table. They will operate on objects. In our program, all tables and classes are mapped together through many-to-one, one-to-many, many-to-many,
4. Talk about the caching mechanism of Hibernate
1. Internal cache is stored in Hibernate, which is also called first-level cache, and belongs to application transaction-level cache.
two。 Second-tier cache:
A) Application and caching
B) distributed cache
Conditions: data will not be modified by third parties, data size is in acceptable range, data update frequency is low, the same data is frequently used by the system, non-critical data
C) implementation of third-party caching
The query mode of 5.Hibernate
The first kind: 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 mapping uses a proxy, the load () method returns an uninitialized proxy until you call the
The database is accessed only when a method of the agent is used. If you want to create an association in one object that points to another object, you don't want to create an association in the
This operation is useful when the object is loaded from the database and the associated object is loaded at the same time. If it is the corresponding class
If the mapping relationship is set to batch-size, then this operation allows multiple objects to be loaded in a batch (because proxies are returned, none
You need to fetch the data of all objects from the database.
If you are not sure if a matching row exists, you should use the get () method, which accesses the database immediately and returns null if there is no corresponding row.
The second kind: HQL
Java code
/ / return a row of records
String hql = "from TOrder o where o.id =?"
TOrder o = (TOrder) s.createQuery (hql)
.setParameter (0, orderId)
.uniqueResult ()
/ / naming 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)
/ / pagination 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 ()
The fourth kind: 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 two-way one-to-many associations instead of one-way one-to-many associations
two。 Flexible use of one-way one-to-many associations
3. Instead of one-to-one, replace it with many-to-one
4. Configure object caching without using collection caching
5. One-to-many collections use Bag and many-to-many collections use Set
6. Inheritance classes use explicit polymorphism
7. Table fields should be few, table associations should not be afraid of too much, and there is a secondary cache to support it.
How does 7.Struts work? Why use Struts?
Working mechanism:
The workflow of Struts:
When the web application starts, it loads and initializes the ActionServlet,ActionServlet from
Read the configuration information in the struts-config.xml file and store it in various configuration objects
When ActionServlet receives a customer request, the following process is performed.
-(1) retrieve the ActionMapping instance that matches the user's request. If it does not exist, the request path is invalid.
-(2) if the ActionForm instance does not exist, create an ActionForm object to save the form data submitted by the customer to the ActionForm object
-(3) decide whether form validation is required according to the configuration information. If verification is needed, call the validate () method of ActionForm
-(4) if the validate () method of ActionForm returns or returns an ActuibErrors object that does not contain ActionMessage, the form is validated successfully
-(5) ActionServlet decides which Action to forward the request to based on the mapping information contained in ActionMapping. If the corresponding Action instance does not exist, create the instance first, and then call the execute () method of Action
-(6) the execute () method of Action returns an ActionForward object, and ActionServlet is forwarding the customer request to the JSP component pointed to by the ActionForward object
-(7) the ActionForward object points to the JSP component to generate a dynamic web page and return it to the customer
Why use:
The emergence of JSP, Servlet and JavaBean technology makes it possible for us to build a powerful enterprise application system. But the system built with these technologies is very complicated, so on top of it, we need a rule, a rule to organize these technologies, this is the framework, and Struts arises at the historic moment.
The application based on Struts consists of three types of components: controller component, model component and view component.
How is 8.Struts 's validate framework verified?
Configure a specific error prompt in the struts configuration file, and then call the validate () method in FormBean.
9. Talk about the design pattern of Struts
MVC mode: ActionServler is loaded and initialized when the web application starts. When the user submits the form, a configured ActionForm object is created and filled in the corresponding data of the form. ActionServler decides whether to validate the form according to the settings configured in the Struts-config.xml file. If necessary, call Validate () of ActionForm to verify and choose which Action to send the request to. If Action does not exist, ActionServlet will first create this object, and then call the execute () method of Action. Execute () gets the data from the ActionForm object, completes the business logic, and returns an ActionForward object. ActionServlet forwards the customer request to the jsp component specified by the ActionForward object, and the jsp specified by the ActionForward object generates a dynamic web page and returns it to the customer.
How 10.spring works and why it should be used?
1.spring mvc asks all requests to be submitted to DispatcherServlet, and it entrusts other modules of the application system with the real processing of the request.
2.DispatcherServlet queries one or more HandlerMapping to find the Controller that processes the request.
3.DispatcherServlet, please request to submit to the target Controller.
After business logic processing, 4.Controller will return a ModelAndView
5.Dispathcher queries one or more ViewResolver view parsers to find the view object specified by the ModelAndView object
6. The view object is responsible for rendering and returning to the client.
Why use:
{AOP allows developers to create non-behavioral concerns called crosscutting concerns and insert them into application code. With AOP, common services (such as logging, persistence, transactions, etc.) can be decomposed into aspects and applied to domain objects without adding complexity to the object model of domain objects.
IOC allows you to create an application environment where objects can be constructed, and then pass their collaborative objects to those objects. As the word inversion shows, IOC is like the reverse JNDI. Instead of using a bunch of abstract factories, service locators, single elements (singleton), and direct constructs (straight construction), each object is constructed from its collaborating object. Therefore, it is a container-managed collaboration object (collaborator).
Spring is an IOC container even if it is an AOP framework. The best thing about Spring is that it helps you replace objects. With Spring, simply add dependencies (collaboration objects) with JavaBean properties and configuration files. You can then easily replace collaboration objects with similar interfaces when needed. }
=
1. HttpSession session = request.getSession ()
The difference from HttpSession session = request.getSession (true)?
Reference answer:
The function prototype of getSession (true) is: HttpSession session = request.getSession (Boolean create)
If there is a HttpSession associated with the current request, the HttpSession associated with the request is returned. If not, then:
Java code
Compared with the current
If create==true, return a newly created HttpSession
If create==false, then return null.
2. What is the difference between getParameter and getAttribute?
Reference answer:
Attribute refers to attributes.
Parameter is a parameter that is passed in by URL or submitted by FORM
3. Which of the following is not an assignment symbol?
A. + = B. 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 when the speed of conditional query is very slow in the database?
1. Build an index
two。 Reduce the association between tables
3. Optimize sql, try to make sql locate data quickly, don't let sql do full table query, you should go to index and put tables with large amount of data in front.
4. Simplify the query fields, do not use the useless fields, have control over the returned results, and return a small amount of data as much as possible
[2. When querying multiple tables in hibernate, how many fields are taken from each table, that is to say, the result set of the query does not have an entity class corresponding to it? how to solve this problem?
Solution one: extract the data according to the Object [] data, and then group the bean yourself.
The second solution is to write a constructor for the bean of each table. For example, if Table 1 wants to find out the two fields of field1,field2, then one constructor is Bean (type1 filed1,type2 field2), and then the bean can be generated directly in hql. Please see the relevant documentation on how to use it. What I said is not very clear.
The difference between session.load () and session.get ()
The Session.load/get method reads the record 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 an ObjectNotFoundException.
The Load method returns an instance of the proxy class of the entity, while the get method always returns the entity class directly.
The load method can make full use of the existing data in the internal cache and the secondary cache, while the get method only looks up the data in the internal cache. If no corresponding data is found, it will go beyond the secondary cache and call SQL directly to complete the data reading.
The process that Session will go through when loading solid objects:
First, two levels of caching are maintained in Hibernate. The first-level cache is maintained by the Session instance, which holds the data of all Session's current associated entities, also known as internal caching. The second-level cache exists in the SessionFactory hierarchy and is shared by all current Session instances constructed by this SessionFactory. For performance reasons and avoid unnecessary database access, Session will query in the cache before invoking the database query function. First of all, in the first-level cache, the lookup is carried out through the entity type and id, and if the first-level cache lookup hits, and the data state is legal, it is returned directly.
Session then looks in the current "NonExists" record and returns null if the same query condition exists in the "NonExists" record. "NonExists" records the query conditions under which the current Session instance failed to query valid data in all previous query operations (equivalent to a query blacklist). In this way, if an invalid query condition repeats in Session, a quick judgment can be made to achieve 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, a database query operation (Select SQL) is initiated. If the corresponding record is not found after the query, the information of the query is recorded in "NonExists" and returned to null.
Create the corresponding data object according to the mapping configuration and the ResultSet obtained by Select SQL.
Incorporate its data objects into the current Session entity management container (level 1 cache).
Execute the Interceptor.onLoad method (if there is a corresponding Interceptor).
Include data objects in the secondary 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 without the involvement of Hibernate.
2) hilo
The primary key generation mechanism realized by hi/lo algorithm requires additional database tables to save the historical state of primary key generation.
3) seqhilo
Similar to hilo, the primary key generation mechanism implemented by the hi/lo algorithm, except that the historical state of the primary key is saved in Sequence, is suitable for databases that support Sequence, such as Oracle.
4) increment
The primary key is incremented in numerical order. The implementation mechanism of this approach is to maintain a variable in the current application instance to hold the current maximum value, and then add this value to 1 as the primary key each time the primary key needs to be generated. The problem that may arise from this approach is that if multiple instances currently access the same database, different instances may generate the same primary key because each instance maintains its own primary key state, resulting in repeated primary key exceptions. Therefore, if multiple instances of the same database are accessed, this method must be avoided.
5) identity
The primary key generation mechanism provided by the database is adopted. Such as the primary key generation mechanism in DB2, SQL Server, and MySQL.
6) sequence
The primary key is generated by the sequence mechanism provided by the database. Such as Sequence in Oralce.
7) native
According to the underlying database, Hibernate decides to use one of identity, hilo and sequence as the primary key generation method.
8) uuid.hex
The hexadecimal value (encoded as a string of length 32) is generated by Hibernate based on the 128bit unique value generation algorithm as the primary key.
9) uuid.string
Similar to uuid.hex, except that the generated primary key is not encoded (length 16). Problems may occur in some databases (such as PostgreSQL).
10) foreign
Use the fields of the external table as the primary key. In general, using uuid.hex to generate primary keys will provide the best performance and database platform adaptability.
Among the 10 methods to generate OID identifiers, increment is more commonly used. The authority to generate identifiers is handed over to Hibernate. But when multiple Hibernate applications operate on the same database or even the same table at the same time. It is recommended to use identity to rely on the underlying database, but the database must support automatic growth, and of course choose different methods for different databases. If you are not sure what exactly the database you are using supports. You can choose to use native to let Hibernate help you choose identity,sequence, or hilo.
In addition, commonly used databases, such as Oracle, DB2, SQLServer, MySql, etc., provide an easy-to-use primary key generation mechanism (Auto-Increase field or Sequence). We can adopt the primary key generation mode of generator-class=native on the primary key generation mechanism provided by the database.
It is worth noting, however, that the primary key generation mechanisms provided by some databases may not be the best in terms of efficiency, and large amounts of concurrent insert data may cause interlocks between tables. The primary key generation mechanism provided by the database is often by saving the current primary key state in an internal table (for example, for a self-increasing primary key, the current maximum and increment are maintained in this internal table). After that, each time the data is inserted, the maximum value is read, and then the recursive increment is added as the primary key of the new record, and then the new maximum value is updated back to the internal table. An Insert operation may lead to multiple table read and write operations within the database, accompanied by data locking and unlocking operations, which 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.
How Hibernate works and why it should be used?
Principle:
1. Read and parse the configuration file
two。 Read and parse the mapping information and create a SessionFactory
3. Open Sesssion
4. Create a transaction Transation
5. Persistence operation
6. Commit transaction
7. Close Session
8. Close SesstionFactory
Why use:
1. The code of JDBC accessing database is encapsulated, which greatly simplifies the tedious and repetitive code of the data access layer.
2. Hibernate is a mainstream persistence framework based on JDBC and an excellent ORM implementation. It greatly simplifies the coding of the DAO layer.
3. Hibernate uses the Java reflection mechanism instead of a bytecode enhancer to achieve transparency.
4. Hibernate's performance is very good because it is a lightweight framework. The flexibility of 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 delay loading implementation: a) entity objects b) collections (Collection)
2. Hibernate3 provides delayed loading of attributes.
When Hibernate is querying the data, the data does not exist in memory. When the program really operates on the data, the object exists in memory, which realizes delayed loading. It saves the memory overhead of the server, thus improving the performance of the server.
3. How to implement the relationship between classes in Hibernate? (e. G. an one-to-many, many-to-many relationship)
The relationship between class and class is mainly reflected in the operation of the relationship between table and table. They will operate on objects. In our program, all tables and classes are mapped together through many-to-one, one-to-many, many-to-many,
4. Talk about the caching mechanism of Hibernate
1. Internal cache is stored in Hibernate, which is also called first-level cache, and belongs to application transaction-level cache.
two。 Second-tier cache:
A) Application and caching
B) distributed cache
Conditions: data will not be modified by third parties, data size is in acceptable range, data update frequency is low, the same data is frequently used by the system, non-critical data
C) implementation of third-party caching
5. Query method of Hibernate
Sql 、 Criteria,object comptosition
Hql:
1. Attribute query
2. Parameter query, named parameter query
3. Association query
4. Paging query
5. Statistical function
At this point, the study of "what are the common interview questions for Spring,hibernate,struts" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.