Hibernate Interview Questions and answers
Essence-a large collection of Hibernate Interview Questions and answers
1. What is the matching relationship between the relational data model and the Object Model (multiple choice) in general)
A) table corresponds to Class B) record corresponding object C) Table field corresponds to class attribute D) Reference relationship between tables correspondence dependency between classes
2. Which of the following statements about SessionFactory are true? (Multiple options)
A) For each database transaction, you should create A SessionFactory object B) A SessionFactory object corresponds to A data inventory source. C) SessionFactory is a heavyweight Object and should not be created at will. If there is only one data inventory source in the system, you only need to create one. D) the load () method of SessionFactory is used to load persistent objects.
3. There is a Set orders attribute in the Customer class, which is used to store the Order object. In the Customer. hbm. xml file, which element is used to map the orders attribute?
A) B) C) D) <: property>
4. The element has a cascade attribute. If you want Hibernate to cascade objects in the Set, what value should the casecade attribute take? (Single choice)
A) noneB) saveC) deleteD) save-update
5. Which of the following are Session methods?
A) load () B) save () C) delete () D) update () E) open () F) close ()
6. What are the printed results of the following programs? (Single choice)
1. tx = session. beginTransaction ();
2. Customer c1 = (Customer) session. load (Customer. class, new Long (1 ));
3. Customer c2 = (Customer) session. load (Customer. class, new Long (1 ));
4. System. out. println (c1 = c2 );
5. tx. commit ();
6. session. close ();
A) run error, throw exception B) print falseC) print true
7. the following code modifies the name attribute of Customer twice:
7. tx = session. beginTransaction ();
8. Customer customer = (Customer) session. load (Customer. class,
9. new Long (1 ));
10. customer. setName (Jack );
11. customer. setName (Mike );
12. tx. commit ();
How many update statements does Hibernate need to submit to the database to execute the above program? (Single choice)
A) 0 B) 1 C) 2 D) 3
8. What are the States of objects in the persistence layer? (Multiple options)
A) Temporary State B) Independent State C) Free State D) persistent state
9. In the following procedure, when does the Customer object change to a persistent state? (Single choice)
13. Customer customer = new Customer (); // line1
14. customer. setName (Tom); // line2
15. Session session1 = sessionFactory. openSession (); // line3
16. Transaction tx1 = session1.beginTransaction (); // line4
17. session1.save (customer); // line4
18. tx1.commit (); // line5
19. session1.close (); // line6
A) line1 B) line2 C) line3 D) line4 E) line5 F) line6
10. In the following procedure, when does the Customer object change to a free state? (Single choice)
20. Customer customer = new Customer (); // line1
21. customer. setName (Tom); // line2
22. Session session1 = sessionFactory. openSession (); // line3
23. Transaction tx1 = session1.beginTransaction (); // line4
24. session1.save (customer); // line4
25. tx1.commit (); // line5
26. session1.close (); // line6
A) line1 B) line2 C) line3 D) line4 E) line5 F) line6
11. Which of the following retrieval policies uses external link queries? (Single choice)
A) instant retrieval B) Delayed retrieval C) Urgent left outer link Retrieval
12. Assume that a delayed retrieval policy is used for the orders set of the Customer class to compile or run the following program)
27. Session session = sessionFactory. openSession ();
28. tx = session. beginTransaction ();
29. Customer customer = (Customer) session. get (Customer. class, new Long (1 ));
30. tx. commit ();
31. session. close ();
32. Iterator orderIterator = customer. getOrders (). iterator ();
A) compilation error B) Compilation succeeded and C) Compilation succeeded, but an exception is thrown during runtime.
13. Which of the following statements about HQL and SQL are true? (Multiple options)
A) There is no difference between HQL and SQL. B) HQL is object-oriented, while SQL is used to manipulate relational database. C) Both HQL and SQL contain select, insert, update, and delete statements. D) HQL is only used to query data and does not support insert, update, and delete statements.
14. who implements the transaction isolation level? (Single choice)
A) Java application B) Hibernate C) Database System D) JDBC driver
15. Which of the following has good concurrency performance? (Single choice)
A) pessimistic lock B) optimistic lock
Answer:
(1) A, B, C (2) B, C (3) A (4) D (5) A, B, C, D, F (6) C (7) B (8) A, C, D (9) D (10) F (11) C (12) C (13) B, D (14) C (15) B
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. The code for JDBC database access is encapsulated, which 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 the bytecode enhancement program to 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
SQL, Criteria, object comptosition
Hql:
1. query attributes
2. parameter query and name parameter query
3. join query
4. Paging Query
5. Statistical functions
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 ActionForm returns null or an ActuibErrors object that does not contain ActionMessage is returned, 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 .}
The Spring framework is a layered architecture consisting of seven well-defined modules. The Spring module is built on the core container. The core container 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 independently or be implemented together with one or more 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 mode. BeanFactory uses the control reversal (IOC) mode to separate application configuration and dependency specifications from 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, checksum and scheduling.
☆Spring AOP: Through the configuration management feature, the Spring AOP module directly integrates Aspect-oriented programming functions into the Spring framework. Therefore, any objects managed by the Spring framework can easily 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 applications without relying on EJB components.
☆Spring DAO: The jdbc dao abstraction layer provides a meaningful exception hierarchy for managing Exception Handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the number of Exception Code to be written (for example, opening and closing connections ). JDBC-oriented exceptions of Spring DAO 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 the general transactions and DAO exception hierarchies of Spring.
☆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 processing multiple 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 policy interface, the MVC framework becomes highly configurable. MVC supports a large number of view technologies, including JSP, Velocity, Tiles, iText, and POI.
The functions of the Spring framework can be used on any J2EE server. Most of the functions are also applicable to unmanaged environments. Spring supports reusable services and data access objects that are not bound to a specific J2EE service. There is no doubt that such objects can be reused between different J2EE environments (Web or EJB), independent applications, and test environments.
IOC and AOP
The basic concept of the inversion mode (also known as dependency intervention) is to describe how to create objects without creating them. The Code does not directly connect to objects and services, but describes which component needs which service in the configuration file. Containers (IOC containers in the Spring framework) are responsible for connecting these together.
In a typical IOC scenario, the container creates all objects and sets the necessary properties to connect them together to determine the time to call the method. The following table lists an implementation mode of IOC.
The IOC container of the Spring framework is implemented by Type 2 and Type 3.
Aspect-Oriented Programming
Aspect-oriented programming (AOP) is a programming technology that allows programmers to modularize the behavior of cross-concern or cross-common division of duties (such as log and transaction management. The core structure of AOP is aspect, which encapsulates the behaviors that affect multiple classes into reusable modules.
AOP and IOC are complementary technologies that use modular methods to solve complex problems in enterprise application development. In a typical object-oriented development method, you may need to place the logging statement in all methods and Java classes to implement the logging function. In the AOP mode, the log service can be modularized in turn and applied to the components that require logs in declarative mode. Of course, the advantage is that the Java class does not need to know the existence of the log service or consider the relevant code. Therefore, application code written with Spring AOP is loosely coupled.
The functions of AOP are fully integrated into the context of Spring transaction management, logs, and other features.
IOC container
The core of Spring design is the org. springframework. beans package, which is designed to be used with the JavaBean Component. This package is usually not directly used by users, but is used by the server as the underlying 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 the creation and retrieval of objects by name. BeanFactory can also manage relationships between objects.
BeanFactory supports two object models.
□The single-State model provides shared instances for objects with specific names, which can be searched during query. Singleton is the default and most commonly used object model. It is ideal for stateless service objects.
□The prototype model ensures that a separate object is created for each retrieval. When each user needs their own objects, the prototype model is the most suitable.
The concept of bean Factory is that Spring serves as the basis of IOC containers. IOC transfers the responsibility for handling tasks from application code to the framework. As I will demonstrate in the next example, the Spring framework uses the JavaBean attribute 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 common BeanFactory definition is XmlBeanFactory, which loads beans according to the definition in the XML file, as shown in Listing 1.
Listing 1. XmlBeanFactory
BeanFactory factory = new XMLBeanFactory (new FileInputSteam (mybean. xml ));
The Bean defined in the XML file is passively loaded, which means that the bean itself will not be initialized before the bean is needed. To retrieve beans from BeanFactory, you only need to call the getBean () method and input 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 POJO (defined by class name and JavaBean initialization attribute) or FactoryBean. The FactoryBean interface adds an indirect level to applications built using the Spring framework.
IOC example
The simplest way to understand control reversal is to look at its practical application. I used an example to summarize Part 1 of the three-part Spring Series, demonstrate how to inject application dependencies through the Spring IOC container (instead of building them in ).
I started with an online credit account use case. To enable a credit account, you must interact with the following services:
☆Credit level evaluation service, which queries users' credit history information.
☆Remote Information Link Service, insert customer information, connect customer information with credit card and bank information for automatic debit (if needed ).
☆Email Service sends an email about the credit card status to the user.
Three Interfaces
For this example, I assume that the service already exists. Ideally, they are integrated in a loosely coupled manner. The following list shows the application interfaces of the three services.
Listing 3. CreditRatingInterface
Public interface CreditRatingInterface {
Public boolean getUserCreditHistoryInformation (ICustomer iCustomer );
}
The credit level evaluation 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 carried out through the getUrl () method. The URL is set by the bean configuration mechanism of the Spring framework. I will discuss it 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 );
All done! _______________________________________________________________ You are welcome to reprint. I hope to add the original address while you reprint it. Thank you for your cooperation.