How does Hibernate work and why should we use Hibernate?
(Recommendations for more related interview questions: java interview questions and answers)
Working principle:
1. Read and parse Configuration file
2. Read and parse the mapping information, create SessionFactory
3. Open Session
4. Create transaction Transation
5. Persistence operation
6. Submit transaction
7. Close Session
8. Close SesstionFactory
Why use Hibernate (that is, its advantages):
1. The code for JDBC access to the 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 work of the DAO layer
3. hibernate uses the Java reflection mechanism instead of the bytecode enhancement program to achieve transparency.
4. The flexibility of hibernate mapping is excellent. It supports various relational databases, ranging from one-to-one to many-to-many complex relationships.
2. The difference between get and load methods in Hibernate
For the load method, hibernate believes that the data must exist in the database. You can safely use the proxy to delay loading. If you find that during use, If the problem is solved, you can only throw an exception;
hibernate For the get method, hibernate must obtain the real data, otherwise it will return null.
Detailed introduction:
1. For the get method, hibernate will confirm whether the data corresponding to the id exists, first search in the session cache, and then search in the second-level cache, not yet Just query the database and return null if it is not found in the database.
2. When the load method loads the entity object, it is configured according to the class-level lazy attribute on the mapping file (default is true).
Discuss on a case-by-case basis:
(1) If it is true, first search in the Session cache to see if the object corresponding to the id exists. If it does not exist, use lazy loading to return the entity. The proxy class object (the proxy class is a subclass of the entity class and is dynamically generated by CGLIB). When the object is actually used (except for obtaining the OID), the second-level cache and database are then queried. If no matching records are found, an ObjectNotFoundException will be thrown.
(2) If it is false, the search order is the same as the get method, except that if no record that meets the conditions is found in the end, an ObjectNotFoundException will be thrown.
3. How does Hibernate delay loading?
Hibernate3 provides the lazy loading function of properties. When Hibernate queries the data, the data does not exist in the memory. Instead, the object exists in the memory when the program actually operates on the data. This implements lazy loading, which saves the memory overhead of the server, thus Improved server performance.
4. How to realize the relationship between classes in Hibernate?
The relationship between classes is mainly reflected in the relationship between tables and tables. They are all To operate objects, we map all tables and classes together in the program, and they operate through many-to-one, one-to-many, and many-to-many in the configuration file.
5. What is the difference between update() and saveOrUpdate() in Hibernate?
saveOrUpdate():
1. If the object is already persisted in this session, do nothing
2. If there is another object associated with this session Have the same persistent identifier (identifier), throw an exception
3. If the object does not have a persistent identifier (identifier) attribute, call save() on it
4. If the object's The persistent identifier (identifier) indicates that it is a newly instantiated object, and call save()
5. If the object comes with version information (via
update():
is to directly update a free entity object.
6, let’s talk about Hibernate’s caching mechanism.
1. First-level cache: The internal cache exists in Hibernate and is an application transaction-level cache.
2. Second level cache: application level cache, distributed cache.
Usage scenarios: data will not be modified by third parties, data size is within an acceptable range, data update frequency is low, the same data is frequently used by the system, non-critical data
3. Introduce third-party cache (such as ehcache, etc.).
7, How to optimize Hibernate?
1. Use two-way one-to-many association instead of one-way one-to-many
2. Flexibly use one-way one-to-many association
3. No need for one-to-one association , replace with many-to-one
4. Configure object cache, do not use collection cache
5. Use Bag for one-to-many collections, and Set for many-to-many collections
6 . Use explicit polymorphism in inherited classes
7. Have fewer table fields, don’t be afraid of too many table associations, and have the support of second-level cache
8. Let’s talk about hibernate’s lazy loading and openSessionInView
## Open, ensuring the premise of lazy loading in the session.
(Video recommendation:
java course)9, briefly explain the workflow of struts2
1. The client browser sends HTTP ask.
2. According to the web.xml configuration, the request is received by FilterDispatcher.
3. According to the struts.xml configuration, find the Action class and method that needs to be called, and inject the value into Aciton through IoC.
4. Action calls the business logic component to process the business logic. This step includes form verification.
5. After the Action is executed, find the corresponding return result according to the configuration in struts.xml, and jump to the corresponding page.
6. Return HTTP response to the client browser.
10, let’s talk about the design pattern of Struts
MVC pattern
1. ActionServlet will be loaded and initialized when the web application starts;
2. When the user submits the form, a configured ActionForm object is created and filled in with the corresponding data of the form;
3. ActionServlet determines whether a form is required based on the settings configured in the Struts-config.xml file Verify, if necessary, call Validate() of ActionForm and select which Action to send the request to after verification. If the Action does not exist, ActionServlet will first create the object and then call the execute() method of Action;
4, Execute() obtains data from the ActionForm object, completes the business logic, and returns an ActionForward object. ActionServlet then forwards the customer request to the jsp component specified by the ActionForward object;
5. The jsp specified by the ActionForward object generates a dynamic web page , returned to the client.
11, Advantages and Disadvantages of Struts
Advantages:
1. Implement the MVC model with a clear structure, allowing developers to only focus on the implementation of business logic.
2. There are a wealth of tags available. The Struts tag library (Taglib), if used flexibly, can greatly improve development efficiency. In addition, as far as domestic JSP developers are concerned, in addition to using the common tags that come with JSP, they rarely develop their own tags. Perhaps Struts is a good starting point.
3. Page navigation. Page navigation will be a development direction in the future. In fact, doing so will make the context of the system clearer. Through a configuration file, you can grasp the connection between various parts of the entire system, which is of great benefit for later maintenance. This advantage becomes even more obvious when another group of developers takes over the project.
4. Provide Exception handling mechanism.
5. Database connection pool management
6. Support I18N
Disadvantages:
1 . When going to the display layer, you need to configure forward. Every time you go to the display layer, I believe most of them go directly to jsp. When it comes to redirection, you need to configure forward. If there are ten jsps in the display layer, you need to configure it ten times. Struts, and this does not include sometimes directory and file changes, which require re-modification of forward. Note that every time the configuration is modified, the entire project is required to be redeployed, and a server like tomcate must be restarted. If the business changes are complex and frequent System, such operation is unimaginably simple. This is it now. Dozens or hundreds of people are using our system online at the same time. You can imagine how troubled I am.
2. Struts Action must be thread-safe, which only allows one instance to handle all requests. Therefore, all resources used by actions must be uniformly synchronized, which causes thread safety issues.
3. Testing is inconvenient. Each Action of Struts is coupled with the Web layer, so its testing depends on the Web container, and unit testing is also difficult to implement. However, there is a Junit extension tool Struts TestCase that can implement its unit testing.
4. Type conversion. Struts’ FormBean treats all data as String type, and it can use the tool Commons-Beanutils for type conversion. But its conversion is all at the Class level, and the conversion type is not configurable. It is also very difficult to return error messages during type conversion to the user.
5. Too much dependence on Servlet. Struts must rely on ServletRequest and ServletResponse when processing Action, so it cannot get rid of the Servlet container.
6. In terms of front-end expression language. Struts integrates JSTL, so it mainly uses JSTL expression language to obtain data. However, JSTL's expression language is very weak in handling Collection and index properties.
7. It is difficult to control the execution of Action. When Struts creates an Action, it will be very difficult to control its execution order. You may even have to re-write the Servlet to realize your functional requirements.
8. Processing before and after Action execution. When Struts processes Action, it is based on class hierarchies, and it is difficult to operate before and after action processing.
9. Insufficient support for events. In Struts, a form actually corresponds to an Action class (or DispatchAction). In other words: in Struts, a form actually corresponds to only one event. Struts This event method is called application event. Compared with component event, application event is a coarse-grained event.
12, why should we use spring (that is, advantages)?
1. Spring can effectively organize your middle-tier objects, regardless of whether you choose to use EJB. If you are just using Struts or other frameworks specifically designed for J2EE APIs, Spring is committed to solving the rest.
2. Spring can eliminate the excessive use of Singleton that is common in many projects. Excessive use of Singleton reduces the testability and object-orientedness of the system.
3. By handling configuration files in a consistent way across different applications and projects, Spring can eliminate the need for various custom formats of properties files. Have you ever wondered which magic attribute or system property a certain class is looking for, and you have to read Javadoc or even source code to do so? With Spring, you only need to look at the JavaBean properties of the class. The use of Inversion ofControl (discussed below) helps accomplish this simplification.
4. By reducing the cost of programming interfaces rather than classes to almost nothing, Spring can promote the development of good programming habits.
5. Spring is designed to make applications created using it depend as little as possible on its APIs. Most business objects in Spring applications have no dependencies on Spring.
6. Applications built with Spring are easy to unit test.
7. Spring can make the use of EJB an implementation choice rather than an inevitable choice of application architecture. You can choose to use POJOs or local EJBs to implement the business interface without affecting the calling code.
8. Spring helps you solve many problems without using EJB. Spring can provide an EJB replacement, which is suitable for many web applications. For example, Spring can provide declarative transaction management using AOP without going through an EJB container, and if you only need to deal with a single database, you don't even need a JTA implementation.
9. Spring provides a consistent framework for data access, whether using JDBC or O/R mapping products (such as Hibernate).
13. List the several ways you know to implement spring transactions
(1) Programmatic transaction management: It requires manual writing of code and is rarely used in actual development.
(2), Declarative transaction management based on TransactionProxyFactoryBean requires corresponding configuration for each transaction management class
(3), Declarative transaction management based on AspectJ's XML, no need To change the class, just configure it in the XML file
(4), annotation-based declarative transaction management, simple configuration, you need to add annotations to the business layer class
14, talk about Isolation level and propagation behavior of spring transactions
Isolation level:
- DEFAULT uses the default isolation level of the database
- READ_UNCOMMITTED will cause dirty reads and non-repeatable reads and phantom read issues
- READ_COMMITTED will cause repeated reads and phantom reads
- REPEATABLE_READ will cause phantom reads
- SERIALIZABLE is the safest, but the cost is the highest and the performance impact is extremely serious
And propagation line:
- REQUIRED If the transaction exists, it will be integrated into the transaction, if it does not exist, it will create the transaction
- SUPPORTS If the transaction exists, it will be integrated into the transaction, if it does not exist, the transaction will not be created
- If a transaction exists in MANDATORY, it will be integrated into the transaction. If it does not exist, an exception will be thrown.
- REQUIRES_NEW always creates a new transaction
- NOT_SUPPORTED If a transaction exists, it will be suspended and non-execution will continue. Transaction operation
- NEVER always executes non-transactions, and if a transaction currently exists, an exception will be thrown
- NESTED embedded transaction
15. What is the DI mechanism?
Dependency Injection and Inversion of Control are the same concept. Specifically: when a role needs assistance from another role, in the traditional programming process, it is usually called to create an instance of the callee.
But in spring, the work of creating the callee is no longer done by the caller, so it is called inversion of control. The work of creating the callee is done by spring, and then the caller is injected
So it is also called dependency injection.
Spring manages objects in a dynamic and flexible way. There are two ways of injection, setting injection and construction injection.
Advantages of setting injection: intuitive and natural
Advantages of construction injection: the order of dependencies can be decided in the constructor.
16. What is AOP?
Aspect-oriented programming (AOP) improves spring's dependency injection (DI).
Aspect-oriented programming mainly manifests itself in two aspects in spring:
1. Aspect-oriented programming provides declarative transaction management
2.spring supports user-defined aspects
Recommended tutorial: Getting started with java
The above is the detailed content of Summary of the latest SSH framework interview questions in 2023. For more information, please follow other related articles on the PHP Chinese website!