This article tells the classic interview written test questions and their reference answers. Share it for your reference, as follows:
1. How does Hibernate work and why should it be used?
principle:
1. Read and parse configuration files
2. Read and parse the mapping information and create a SessionFactory
3. Open Session
4. Create a transaction Transation
5. Persistence operation
6. Submit transactions
7. Close Session
8. Close SesstionFactory
Why use:
①. The code for JDBC accessing databases has been encapsulated, greatly simplifying the cumbersome repetitive code in the data access layer.
②. Hibernate is a mainstream persistence framework based on JDBC and is an excellent ORM implementation. It greatly simplifies the coding work of the DAO layer to a great extent
③. hibernate uses Java reflection mechanism, rather than bytecode enhancement programs to achieve transparency.
④ . hibernate performs very well because it is a lightweight framework. The flexibility of mapping is excellent. It supports various relational databases, from one to one to many to many complex relationships.
2. How does Hibernate delay loading?
①. Hibernate2 delay loading implementation: a) entity object b) collection (Collection)
②. Hibernate3 provides the delayed loading function of attributes. When Hibernate querys data, the data does not exist and memory. When the program truly operates on the data, the object exists and memory, which realizes delayed loading. It saves the server's memory overhead and thus improves the server's performance.
3. How to implement the relationship between classes in Hibernate? (such as one-to-many, many-to-many relationship)
The relationship between classes is mainly reflected in the relationship between tables. They operate on objects in the city. Our program maps all tables and classes together, and they are passed through many-to-one, one-to-many, many-to-many, and many-to-many in the configuration file.
4. Let's talk about Hibernate's cache mechanism
①. The internal cache is also called first-level cache in Hibernate, which belongs to application-level cache
②. Level 2 cache:
a) Application and cache
b) Distributed cache conditions: data will not be modified by third parties, the data size is within an acceptable range, the data update frequency is low, the same data is frequently used by the system, and non-critical data
c) Implementation of third-party cache
5. Hibernate query method
Sql, Criteria, object comptosition
Hql:
1. Attribute query
2. Parameter query, named parameter query
3. Related Query
4. Pagination query
5. Statistical functions
6. How to optimize Hibernate?
①. Use bidirectional one-to-many association, not one-to-many one-to-many ②. Use flexibly one-to-many one-to-many association ③. Do not use one-to-one, use many-to-one instead ④. Configure object cache, not use set cache ⑤. Use Bag for one-to-many collections, and use Set for many-to-many collections.
⑥. Use explicit polymorphism in inheritance classes⑦. There should be fewer table fields, and don’t be afraid of many table associations. There is a secondary cache to support you.
7. Struts working mechanism? Why use Struts?
Working mechanism:
Struts' workflow:
The initialization ActionServlet will be loaded when the web application is started. The ActionServlet will be loaded from
Read configuration information from the struts-config.xml file and store them in various configuration objects
When the ActionServlet receives a client request, the following process will be executed.
-(1) Retrieve the ActionMapping instance that matches the user request. If it does not exist, it returns the request path invalid information;
-(2) If the ActionForm instance does not exist, create an ActionForm object and save the form data submitted by the client to the ActionForm object;
-(3) Decide whether form verification is needed based on the configuration information. If verification is required, call ActionForm's validate() method;
-(4) If the validate() method of ActionForm returns null or returns an ActuibErrors object that does not contain ActionMessage, it means that the form verification is successful;
-(5) The ActionServlet decides which Action to forward the request based on the mapping information contained in ActionMapping. If the corresponding Action instance does not exist, create this instance first and then call the Action's execute() method;
-(6) Action's execute() method returns an ActionForward object, and the ActionServlet forwards the client 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 returns it to the client;
Why use:
The emergence of JSP, Servlet, and JavaBean technologies provide us with the possibility of building powerful enterprise application systems. But the system built with these technologies is very chaotic, so on top of this, we need a rule and a rule to organize these technologies. This is the framework, and Struts came into being.
Applications developed based on Struts are composed of three types of components: controller components, model components, and view components
8. How is Struts' validate framework validated?
Configure specific error prompts in the struts configuration file, and then call the validate() method in the FormBean.
9. Let's talk about Struts' design pattern
MVC Mode: ActionServler is loaded and initialized when the web application starts. When the user submits a form, a configured ActionForm object is created and filled in the corresponding data of the form. The ActionServler decides whether form verification is needed based on the settings configured by the Struts-config.xml file. If necessary, call ActionForm's Validate() verification and select which Action to send the request to. If the Action does not exist, the ActionServlet will first create this object and then call the Action's execute() method. Execute() obtains data from the ActionForm object, completes business logic, and returns an ActionForward object. The ActionServlet forwards the client request to the jsp component specified by the ActionForward object. The jsp specified by the ActionForward object generates a dynamic web page and returns it to the client.
10. Spring working mechanism and why?
①.spring mvc Please submit all requests to the DispatcherServlet, which will entrust other modules of the application system to be responsible for the actual processing of the request.
②.DispatcherServlet querys one or more HandlerMappings and finds the controller that handles the request.
③.DispatcherServlet Please submit the request to the target controller
④. After the Controller performs business logic processing, it will return a ModelAndView.
⑤.Dispathcher querys one or more ViewResolver view resolvers and finds the view object specified by the ModelAndView object ⑥. The view object is responsible for rendering and returning it to the client.
Why use:
{AOP allows developers to create non-behavioral concerns, called cross-cutting concerns, and insert them into application code. After using AOP, public services (such as logs, persistence, transactions, etc.) can be broken down into aspects and applied to domain objects without increasing the complexity of the object model of domain objects.
IOC allows creating an application environment where objects can be constructed and then passing their collaborative objects to those objects. As the word inversion indicates, IOC is like the reverse JNDI. Without using a bunch of abstract factories, service locators, singletons, and straight construction, each object is constructed with its collaborative objects. Therefore, the collaborator is managed by the container.
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, just add dependencies (collaboration objects) using JavaBean properties and configuration files. Collaboration objects with similar interfaces can then be easily replaced when needed. }
The Spring Framework is a hierarchical architecture consisting of 7 well-defined modules. Spring modules are built on top of core containers that define how beans are created, configured, and managed.
Each module (or component) that makes up the Spring framework can exist alone or be implemented in conjunction with one or more other modules. The functions of each module are as follows:
☆ Core Container: Core Container provides the basic functions of the Spring framework. The main component of the core container is BeanFactory, which is an implementation of the factory pattern. BeanFactory uses the Inversion of Control (IOC) mode to separate the configuration and dependency specifications of an application from the actual application code.
☆ Spring context: The Spring context is a configuration file that provides context information to the Spring framework. Spring context includes enterprise services such as JNDI, EJB, Email, Internationalization, Checksum Scheduling capabilities.
☆ Spring AOP: Through the configuration management feature, the Spring AOP module directly integrates aspect-oriented programming functions into the Spring framework. Therefore, it is easy to make any object managed by Spring framework support AOP. The Spring AOP module provides transaction management services for objects in Spring-based applications. By using Spring AOP, declarative transaction management can be integrated into the application without relying on EJB components.
☆ Spring DAO: The JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code that needs to be written (such as opening and closing connections). Spring DAO's JDBC-oriented exceptions follow the common DAO exception hierarchy.
☆ Spring ORM: The Spring framework inserts several ORM frameworks, thus providing ORM object relationship tools, including JDO, Hibernate, and iBatis SQL Map. All of this follows Spring's common transaction and DAO exception hierarchy.
☆ Spring Web Module: The Web context module is built on the application context module and provides context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies the work of handling multi-part requests and binding request parameters to domain objects.
☆ Spring MVC Framework: The MVC Framework is a fully functional MVC implementation for building web applications. Through the policy interface, the MVC framework becomes highly configurable, and MVC houses a large number of view technologies, including JSP, Velocity, Tiles, iText, and POI.
The Spring framework's capabilities can be used in any J2EE server, and most of them are suitable for unmanaged environments. The core point of Spring is: Support for reusable business and data access objects that are not bound to specific J2EE services. There is no doubt that such objects can be reused between different J2EE environments (Web or EJB), standalone applications, test environments.
IOC and AOP
The basic concept of controlling inversion patterns (also known as dependency intervention) is to not create objects, but describe how they are created. It does not directly connect to objects and services in the code, but describes which component requires which service in the configuration file. Containers (IOC containers in Spring framework) are responsible for linking these together.
In a typical IOC scenario, the container creates all objects and sets the necessary properties to connect them together, deciding when the method is called. The following table lists an implementation pattern of IOC.
The Spring framework's IOC container is implemented using Type 2 and Type 3.
Aspect-oriented programming
Aspect-oriented programming, AOP, is a programming technique that allows programmers to modularize behaviors that cross-cut the concerns or cross-cut typical dividing lines of responsibility (such as logging and transaction management). The core construction of AOP is aspect, which encapsulates those behaviors that affect multiple classes into reusable modules.
AOP and IOC are complementary technologies, both of which use modular approaches to solve complex problems in enterprise application development. In typical object-oriented development, logging statements may be required to place in all methods and Java classes to implement logging functionality. In the AOP approach, log services can be modularized in turn and applied declaratively to components that require logs. Of course, the advantage is that Java classes do not need to know the existence of log services, nor do they need to consider relevant code. Therefore, application code written in Spring AOP is loosely coupled.
The functionality of AOP is fully integrated into the context of Spring transaction management, logging and various other features.
IOC container
At the heart of Spring's design is the org.springframework.beans package, which is designed to be used with JavaBean components. This package is usually not used directly by the user, but by the server using it as the underlying intermediary for most other functions. The next most advanced abstraction is the BeanFactory interface, which is an implementation of the factory design pattern that allows objects to be created and retrieved by names. BeanFactory can also manage relationships between objects.
BeanFactory supports two object models.
□ The singleton model provides shared instances of objects with specific names that can be retrieved when querying. Singleton is the default and most commonly used object model. Ideal for stateless service objects.
□ Prototype model ensures that separate objects are created each time they are retrieved. Prototypes are best suited when each user needs their own object.
The concept of bean factory is the basis of Spring as IOC container. IOC shifts responsibility for handling things from application code to frameworks. As I will demonstrate in the next example, the Spring framework uses JavaBean properties and configuration data to indicate the dependencies that must be set.
BeanFactory interface
Because org.springframework.beans.factory.BeanFactory is a simple interface, it can be implemented for various underlying storage methods. The most commonly used BeanFactory definition is XmlBeanFactory, which loads beans according to the definitions in XML files, as shown in Listing 1.
Listing 1. XmlBeanFactory
BeanFactory factory = new XMLBeanFactory(new FileInputSteam("mybean.xml"));Beans defined in XML files are negatively loaded, meaning that the bean itself will not be initialized until it is needed. To retrieve a bean from BeanFactory, just call the getBean() method and pass in the name of the bean to be retrieved, as shown in Listing 2.
Listing 2. getBean()
MyBean mybean = (MyBean) factory.getBean("mybean");The definition of each bean can be either a POJO (defined with class name and JavaBean initialization property) or a FactoryBean. The FactoryBean interface adds an indirect level to applications built using the Spring framework.
IOC Example
The easiest way to understand control inversion is to look at its practical application. In summarizing Part 1 of the three-part Spring series, I used an example that demonstrates how to inject dependencies of an application through Spring IOC containers (rather than building them in).
I use the use case of opening an online credit account as a starting point. For this implementation, enabling a credit account requires the user to interact with the following services:
☆ Credit level assessment service, query user's credit history information.
☆ Remote information link service, insert customer information, connect customer information with credit card and bank information for automatic debit (if required).
☆ Email service, sending users emails about credit card status.
Three interfaces
For this example, I assume that the services already exist, and ideally it is to integrate them together in a loosely coupled way. The following list shows the application program interfaces for the three services.
Listing 3. CreditRatingInterface
public interface CreditRatingInterface {public boolean getUserCreditHistoryInformation(ICustomer iCustomer);}The credit level assessment interface shown in Listing 3 provides credit history information. It requires a Customer object containing customer information. The implementation of this interface is provided by the CreditRating class.
Listing 4. CreditLinkingInterface
public interface CreditLinkingInterface {public String getUrl();public void setUrl(String url);public void linkCreditBankAccount() throws Exception ;}The credit link interface connects the credit history information with the bank information (if needed) and inserts the user's credit card information. The credit link interface is a remote service, and its query is performed through the getUrl() method. The URL is set by the Spring framework's bean configuration mechanism, which I'll discuss later. The implementation of this interface is provided by the CreditLinking class.
Listing 5. EmailInterface
public interface EmailInterface {public void sendEmail(ICustomer iCustomer);public String getFromEmail();public void setFromEmail(String fromEmail);public String getPassword();public void setPassword(String password);public String getSmtpHost();public void setSmtpHost(String smtpHost);public String getUserId();public void setUserId(String userId);I hope this article will be helpful to everyone's Java programming.