-
How does Hibernate work and why should you use it?
principle:
1. Read and parse the configuration file
2. Read and parse mapping information and create SessionFactory
3.Open Session
4. Create transaction Transation
5. Persistence operations
6. Submit transaction
7.Close Session
8. Close SessionFactory
Why use:
1. The code for JDBC access to the database is encapsulated, which greatly simplifies the tedious and repetitive code in 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 Java reflection mechanism instead of bytecode enhancement program to achieve transparency.
4. The performance of hibernate is very good because it is a lightweight framework. The flexibility of mapping is outstanding. It supports various relational databases, ranging from one-to-one to many-to-many complex relationships.
2. How does Hibernate lazy load?
1. Hibernate2 lazy loading implementation: a) entity object b) collection (Collection)
2. Hibernate3 provides lazy loading function of properties
When Hibernate queries the data, the data does not exist in the memory. When the program actually operates on the data, the object exists in the memory, thus achieving lazy loading. It saves the memory overhead of the server, thereby improving the server's performance. performance.
3. How to realize the relationship between classes in Hibernate? (such as: one-to-many, many-to-many relationship)
The relationship between classes is mainly reflected in the operation of the relationship between tables. They all operate on objects. All tables and classes are mapped together in our program, and they are mapped together through many-to in the configuration file. -one, one-to-many, many-to-many,
4. Let’s talk about Hibernate’s caching mechanism
1. The internal cache exists in Hibernate, also called the first-level cache, which belongs to the application transaction level cache.
2. Second level cache:
a) Application and cache
b) Distributed cache conditions: data will not be modified by a third party, data size is within an acceptable range, data update frequency is low, the same data is frequently used by the system, 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. Paging query
5. Statistical functions
6. How to optimize Hibernate?
1. Use two-way one-to-many association instead of one-way one-to-many association.
2. Flexible use of one-way one-to-many associations
3. Instead of one-to-one, use many-to-one instead.
4. Configure object cache and 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. There should be fewer table fields, don’t be afraid of too many table associations, and have the support of second-level cache.
7. How does Struts work? Why use Struts?
Working mechanism:
Struts workflow:
When the web application starts, the initialization ActionServlet will be loaded. The ActionServlet will start from
Read configuration information from the struts-config.xml file and store them in various configuration objects. When 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, return invalid request path information;
-(2) If the ActionForm instance does not exist, create an ActionForm object and save the form data submitted by the customer into the ActionForm object;
-(3) Determine whether form validation is required based on the configuration information. If validation is required, call the validate() method of ActionForm;
-(4) If the validate() method of ActionForm returns null or returns an ActuibErrors object that does not contain an ActionMessage, it means that the form validation is successful;
-(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, first create this instance and then call the Action's execute() method;
-(6) Action's execute() method returns an ActionForward object, and ActionServlet forwards 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 returns it to the customer;
Why use:
The emergence of JSP, Servlet, and JavaBean technologies makes it possible for us to build powerful enterprise application systems. But the systems built with these technologies are very complicated, so on top of this, we need a rule, 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 does Struts' validate framework verify?
Configure specific error prompts in the struts configuration file, and then specifically call the validate() method in FormBean.
9. Let’s 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 with the corresponding data of the form. ActionServler determines whether form validation is required based on the settings configured in the Struts-config.xml file. If necessary, it calls Validate() of ActionForm. After verification, select which Action to send the request to. 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, and returns an ActionForward object. 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 web page and returns it to the customer.
10. How does spring work and why should it be used?
1. Spring MVC asks all requests to be submitted to DispatcherServlet, which will entrust other modules of the application system to be responsible for the actual processing of the requests.
2.DispatcherServlet queries one or more HandlerMapping to find the Controller that handles the request.
3.DispatcherServlet please submit the request to the target Controller
4. After the Controller performs business logic processing, it 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 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 logging, persistence, transactions, etc.) can be decomposed into aspects and applied to domain objects without increasing the complexity of the object model of domain objects.
IOC allows the creation of an application environment that can construct objects and then pass these objects their collaborating objects. As the word inversion indicates, IOC is like JNDI in reverse. Instead of using a bunch of abstract factories, service locators, singletons, and straight construction, every object is constructed from its collaborating objects. Therefore, the container manages the collaboration object (collaborator).
Even though Spring is an AOP framework, it is also an IOC container. The best thing about Spring is that it helps you replace objects. With Spring, just add dependencies (collaborating objects) using JavaBean properties and configuration files. It is then easy to replace collaborating objects with similar interfaces when needed. }
Spring framework is a layered architecture consisting of 7 well-defined modules. Spring modules are built on top of the core container, which defines how to create, configure, and manage beans, as shown in Figure 1.
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: The core container provides the basic functions of the Spring framework. The main component of the core container is BeanFactory, which is the implementation of the factory pattern. BeanFactory uses the Inversion of Control (IOC) pattern to separate the application's configuration and dependency specifications from the actual application code.
☆ Spring context: 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, validation, and dispatch functions.
☆ Spring AOP: Through configuration management features, the Spring AOP module directly integrates aspect-oriented programming functions into the Spring framework. Therefore, it is easy to make any object managed by the Spring framework support AOP. The Spring AOP module provides transaction management services for objects in Spring-based applications. By using Spring AOP, you can integrate declarative transaction management into your 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 to provide ORM object-relational tools, including JDO, Hibernate and iBatis SQL Map. All of these comply with Spring's generic 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, Spring framework supports integration with Jakarta Struts. The web module also simplifies handling multipart requests and binding request parameters to domain objects.
☆ Spring MVC framework: The MVC framework is a full-featured MVC implementation for building Web applications. Through the strategy interface, the MVC framework becomes highly configurable, and MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, iText, and POI.
Spring Framework features can be used in any J2EE server, and most features are also suitable for unmanaged environments. The core point of Spring is to support reusable business and data access objects that are not tied to specific J2EE services. There is no doubt that such objects can be reused between different J2EE environments (Web or EJB), stand-alone applications, and test environments.
IOC and AOP
The basic concept of the Inversion of Control pattern (also called dependency intervention) is that you don't create objects, but you describe how to create them. It is not directly connected to objects and services in the code, but which component requires which service is described in the configuration file. The container (in the Spring framework, the IOC container) is responsible for tying these together.
In a typical IOC scenario, the container creates all the objects and sets the necessary properties to connect them together and decide when to call methods. The following table lists an implementation mode of IOC.
The Spring framework's IOC container is implemented using type 2 and type 3.
aspect-oriented programming
Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize behaviors that cut across concerns or typical lines of responsibility, such as logging and transaction management. The core construct of AOP is aspects, which encapsulate behavior that affects multiple classes into reusable modules.
AOP and IOC are complementary technologies that use a modular approach to solve complex problems in enterprise application development. In a typical object-oriented development approach, logging statements may be placed in all methods and Java classes to implement logging functionality. In the AOP approach, logging services can in turn be modularized and applied declaratively to components that require logging. Of course, the advantage is that the Java class does not need to know the existence of the log service, nor does it need to consider related 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
The core of Spring's design is the org.springframework.beans package, which is designed for use with JavaBean components. This package is usually not used directly by the user, but is used by the server as a low-level intermediary for most other functions. The next highest level abstraction is the BeanFactory interface, which is an implementation of the Factory design pattern and allows objects to be created and retrieved by name. BeanFactory can also manage relationships between objects.
BeanFactory supports two object models.
□ The monomorphic model provides a shared instance of an object with a specific name that can be retrieved at query time. Singleton is the default and most commonly used object model. Ideal for stateless service objects.
□ The prototype model ensures that a separate object is created for each retrieval. The prototype model is best suited when each user needs his or her own object.
The concept of bean factory is the basis of Spring as an IOC container. IOC transfers the responsibility of handling things from the application code to the framework. As I will demonstrate in the next example, the Spring framework uses JavaBean properties and configuration data to indicate which dependencies 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 based on definitions in an XML file, as shown in Listing 1.
Listing 1. XmlBeanFactory
BeanFactory factory = new XMLBeanFactory(new FileInputSteam("mybean.xml"));
Beans defined in XML files are passively loaded, which means that the bean itself is not initialized until the bean is needed. To retrieve a bean from the BeanFactory, simply call the getBean() method, passing in the name of the bean to be retrieved, as shown in Listing 2.
Listing 2. getBean()
MyBean mybean = (MyBean) factory.getBean("mybean");
Each bean definition can be a POJO (defined with a class name and JavaBean initialization properties) or a FactoryBean. The FactoryBean interface adds a level of indirection to applications built using the Spring framework.
IOC example
The easiest way to understand inversion of control is to see it in action. I concluded Part 1 of my three-part Spring series with an example that demonstrates how to inject your application's dependencies (instead of building them in) through the Spring IOC container.
I used the use case of opening an online credit account as a starting point. For this implementation, opening a credit account requires the user to interact with the following services:
☆Credit rating service, query user’s credit history information.
☆ Remote message linking service to insert customer information and connect customer information with credit card and bank information for automatic debit (if required).
☆ Email service to send emails about credit card status to users.
three interfaces
For this example, I'm assuming the services already exist and ideally integrate them in a loosely coupled way. The following listing shows the APIs for the three services.
Listing 3. CreditRatingInterface
public interface CreditRatingInterface {
public boolean getUserCreditHistoryInformation(ICustomer iCustomer);
}
The credit rating 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 linking interface joins credit history information with banking information (if required) 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 will 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);
This article comes from the CSDN blog. Please indicate the source when reprinting: http://blog.csdn.net/loshu2003/archive/2009/12/31/5111344.aspx
-