Hibernate face questions and Answers

Source: Internet
Author: User
Tags throw exception to domain

The essence-hibernate the question and the answer big collection


1. In general, what are the matching relationships between the relational data model and the object model (multiple selection)
A) table corresponding to Class B) record corresponding object C) table field corresponding to the class's attribute D) the reference relationship between tables corresponds to the dependency between classes


2. Which of the following statements about Sessionfactory are correct? (Multiple selection)
A) For each database transaction, you should create a Sessionfactory object B) A Sessionfactory object corresponding to a database storage source. C) Sessionfactory is a heavyweight object and should not be created arbitrarily. If there is only one database storage source in the system, you only need to create one. D) the Sessionfactory load () method is used to load the persisted object


There is a set type of orders property in the 3.Customer class that holds the order object, and in the Customer.hbm.xml file, which element is used to map the orders property?
A) B) C) D) <:p roperty>


4. The element has a cascade property, what value should the Casecade attribute take if you want Hibernate to cascade to save the objects in the collection? (Single radio)
A) noneb) Savec) DeleteD) save-update


5. Which of the following sessions are part of the session?
A) load () B) Save () C) Delete () D) update () E) open () F) Close ()


6. What are the printing results of the following programs? (radio)
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 program code has been modified two times for the customer's Name property:
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 ();
To execute the above procedure, hibernate needs to submit several update statements to the database? (Single radio)
A) 0 B) 1 C) 2 D) 3


8. In the persistence layer, what states are the objects divided into? (Multiple selection)
A) temporary State B) independent status C) Free State d) Persistent state


9. For the following program, the customer object becomes persisted in the first few lines? (Single radio)
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. For the following procedure, the Customer object becomes free in the first few lines? (radio)
20.Customer Customer=new customer (); Line1
21st.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 search strategies take advantage of an external link query? (radio)
A) Immediate retrieval B) deferred retrieval C) urgent left-side link search


12. Assume that a deferred retrieval policy is used for the orders collection of the customer class, and what happens if you compile or run the following program (radio)
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) Compile error B) compile pass, and normal run C) compile pass, but runtime throws exception


13. About HQL and SQL, which of the following statements is correct? (Multiple selection)
A) HQL and SQL no difference b) HQL object-oriented, SQL manipulation relational database C) in HQL and SQL, both contain select,insert,update,delete statement D) hql only for querying data, does not support insert, Update and DELETE statements


14. Who is the transaction isolation level implemented by? (Single radio)
A) Java application B) Hibernate C) database system D) JDBC Driver


15. Pessimistic lock and optimistic lock, which has good concurrency performance? (Single radio)
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 (+) F (one) c (+) C (+) B,d (+) C (+) b






How does hibernate work and why should I use it?
Principle:
1. Read and parse the configuration file
2. Read and parse mapping information, create Sessionfactory
3. Open Sesssion
4. Create Transaction Transation
5. Persistent operation
6. Commit a transaction
7. Close session
8. Close Sesstionfactory


Why to use:
1. The code for JDBC access to the database is encapsulated, which greatly simplifies the tedious repetitive code of the data access layer.


2. Hibernate is a JDBC-based, mainstream persistence framework that is an excellent ORM implementation. He simplifies the coding of the DAO layer to a great extent


3. Hibernate uses the Java reflection mechanism rather than the bytecode enhancer to achieve transparency.


4. Hibernate performs very well because it is a lightweight framework. The flexibility of the 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 Deferred load implementation: a) collection of entity object B) (Collection)


2. Hibernate3 provides properties for lazy loading functions


When hibernate is querying the data, the data does not exist in memory, and when the program actually operates on the data, the object exists in memory, and the delay is loaded, which saves the server's memory overhead and improves the performance of the server.


3. How do the relationships between classes be implemented in hibernate? (e.g. one-to-many, many-to-many relationships)


The relationship between classes and classes is mainly manifested in the relationship between tables and tables, they operate on objects, and in our program we map all the tables and classes together, through the Many-to-one, One-to-many, Many-to-many,


4. The caching mechanism of hibernate


1. Internal cache exists Hibernate is also called a first-level cache, belongs to the application of the thing-level cache


2. Level Two cache:
A) application and caching
b) Distributed cache
Conditions: Data is not modified by third parties, data size is acceptable, data update frequency is low, the same data is frequently used by the system, non-critical data
c) Implementation of third-party caches


5. How hibernate is queried
SQL, Criteria,object comptosition
HQL:
1. Attribute Query
2, parameter query, named parameter query
3. Related queries
4, paging query
5. Statistical functions


6. How to optimize hibernate?
1. Use bidirectional one-to-many associations without using
2. Flexible use of unidirectional one-to-many associations
3. Do not use one-to-many substitution
4. Configure the object cache without using the collection cache
5. One-to-many collection using bag, multi-set using Set
6. Inheriting classes using explicit polymorphism
7. Table fields are less, tables associated not afraid of more, there is a level two cache backing




7. Struts working mechanism? Why use struts?
Working mechanism:
The work flow of struts:
When the web app starts, it loads the initialization actionservlet,actionservlet from
Struts-config.xml files to read configuration information and store them in various configuration objects
When Actionservlet receives a customer request, the following process is executed.
-(1) Retrieval and user request matching actionmapping instance, if not present, return the request path invalid information;
-(2) If the Actionform instance does not exist, create a Actionform object and save the form data submitted by the client to the Actionform object;
-(3) Determine if form validation is required based on configuration information. If validation is required, call Actionform's validate () method;
-(4) If Actionform's Validate () method returns null or returns a Actuiberrors object that does not contain actionmessage, the form validation is successful;
-(5) Actionservlet determines which action to forward the request to, based on the mapping information contained in the actionmapping, and if the corresponding action instance does not exist, create the instance first and then invoke the Execute () method of the action;
-(6) The Execute () method of the action returns a Actionforward object that actionservlet the JSP component to which the client request is forwarded to the Actionforward object;
-(7) The Actionforward object points to the JSP component to generate a Dynamic Web page, which is returned to the customer;


Why to use:
The advent of JSP, Servlet, and JavaBean technology gives us the possibility to build powerful enterprise application systems. But the systems built with these techniques are very fanluan, so on top of that, we need a rule, a rule that organizes these technologies, and that is the framework in which struts emerges.


Struts-based applications consist of 3 types of components: Controller components, model components, view components


8. How is the validate framework of struts validated?
Configure specific error prompts in the struts configuration file, and then invoke the Validate () method in Formbean.


9. The design pattern of struts
MVC mode: Actionservler is loaded and initialized when the Web application starts. When a user submits a form, a configured Actionform object is created and populated with the corresponding data in the form. Actionservler determines whether form validation is required based on the settings configured for the Struts-config.xml file, and if necessary, select the action to which the request is sent if the Validate () validation is called Actionform, if the action does not exist , Actionservlet creates the object first and then invokes the Execute () method of the action. Execute () Gets the data from the Actionform object, completes the business logic, returns a Actionforward object, actionservlet the client request to the JSP component specified by the Actionforward object, The Actionforward object specifies that the JSP generates a dynamic Web page that is returned to the customer.


10. Spring working mechanism and why should it be used?
1.spring MVC requests that all requests be submitted to Dispatcherservlet, which will delegate the other modules of the application system responsible for the actual processing of the request.
2.DispatcherServlet queries one or more handlermapping to find the controller that handles the request.
3.DispatcherServlet request Submit to target Controller
4.Controller after the business logic is processed, it returns a Modelandview
5.Dispathcher querying one or more viewresolver view resolvers, locating the View object specified by the Modelandview object
6. The View object is responsible for rendering back to the client.


Why use:
{AOP allows developers to create non-behavioral concerns, called crosscutting concerns, and insert them into application code. With AOP, public services (such as logs, persistence, transactions, and so on) can be decomposed into facets and applied to domain objects without increasing the complexity of the object model of the domain object.
IOC allows you to create an application environment where objects can be constructed, and then pass their collaboration objects to those objects. As the word inversion shows, the IOC is like the reverse JNDI. Not using a bunch of abstract factories, service locators, single elements (singleton), and direct constructs (straight construction), each object is constructed with its collaboration objects. Therefore, the collaboration object (collaborator) is managed by the container.
Spring even an AOP framework, is also an IOC container. The best part of Spring is that it helps you replace objects. With Spring, you simply add dependencies (collaboration objects) with the JavaBean property and configuration file. You can then easily replace collaboration objects with similar interfaces when you need them. }








The Spring framework is a layered architecture consisting of 7 well-defined modules. The Spring modules are built on top of the core container, and the core container defines how the beans are created, configured, and managed, as shown in 1.


Each module (or component) that makes up the Spring framework can exist separately 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. The beanfactory uses the inversion of control (IOC) pattern to separate the application's configuration and dependency specifications from the actual application code.


☆spring Context: The spring context is a configuration file that provides contextual information to the spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internationalization, checksum scheduling.


☆spring AOP: With the configuration management feature, the Spring AOP module directly integrates aspect-oriented programming capabilities into the spring framework. Therefore, it is easy to enable any object managed by the Spring framework to 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.


The ☆spring dao: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 number of exception codes that need to be written (such as opening and closing connections). Spring DAO's JDBC-oriented exception conforms to the common DAO exception hierarchy.


The ☆spring orm:spring Framework inserts several ORM frameworks, providing an ORM object-relational tool that includes JDO, Hibernate, and IBatis SQL Map. All of these conform to Spring's common transaction and DAO exception hierarchies.


☆spring Web module: The Web context module is built on top of the application context module and provides the context for Web-based applications. Therefore, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies the process of working with multipart requests and binding request parameters to domain objects.


☆spring MVC framework: The MVC Framework is a full-featured MVC implementation of building WEB applications. With the policy interface, the MVC framework becomes highly configurable, and MVC accommodates a large number of view technologies, including JSP, Velocity, Tiles, IText, and POI.


The functionality of the Spring framework can be used in any Java EE server, and most features are also available in an out-of-management environment. The core point of Spring is to support reusable business and data access objects that are not tied to a particular Java EE service. There is no doubt that such objects can be reused across different Java EE environments (Web or EJB), standalone applications, and test environments.


IOC and AOP


The basic concept of control reversal mode (also known as dependency intervention) is that you do not create objects, but describe how they are created. The code does not directly connect to objects and services, but describes in the configuration file which component requires which service. Containers (which are IOC containers in the Spring framework) are responsible for linking these together.


In a typical IOC scenario, the container creates all the objects and sets the necessary properties to connect them together, deciding when to invoke the method. The following table lists an implementation pattern for the IOC.








The IOC container for the Spring framework is implemented with type 2 and type 3.




Aspect-oriented programming


Aspect-oriented programming, AOP, is a programming technique that allows programmers to modularize the behavior of crosscutting concerns or crosscutting typical lines of responsibility, such as logging and transaction management. The core structure of AOP is the facet, which encapsulates behaviors that affect 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 in order to implement logging functionality. In the AOP approach, the log service can be modularized in turn and applied declaratively to the component that needs the log. Of course, the advantage is that the Java class does not need to know the existence of the log service and does not need to consider the associated 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 the Spring design is the Org.springframework.beans package, which is designed to be used with the JavaBean component. This package is not usually used directly by the user, 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 the implementation of the factory design pattern, allowing objects to be created and retrieved by name. Beanfactory can also manage the relationships between objects.


The beanfactory supports two object models.


-a single-state model provides a shared instance of an object with a specific name, which 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 each retrieval creates a separate object. The prototype model works best when each user needs his or her own object.


The Bean Factory concept is the basis of Spring as an IOC container. The IOC shifts responsibility for handling things from application code to frameworks. As I will demonstrate in the next example, the Spring framework uses the JavaBean property 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 a variety of underlying storage methods. The most commonly used beanfactory definition is xmlbeanfactory, which loads the bean 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 beans defined in the XML file are negatively loaded, which means that the bean itself will not be initialized until the bean is needed. To retrieve a bean from beanfactory, simply call the Getbean () method and pass in the name of the bean that will be retrieved, as shown in Listing 2.


Listing 2. Getbean ()


Mybean Mybean = (Mybean) factory.getbean ("Mybean");


Each bean definition can be POJO (with the class name and JavaBean initialization property definition) or Factorybean. The Factorybean interface adds an indirect level for applications built using the Spring framework.


IOC Example


The simplest way to understand control inversion is to look at its practical application. In summarizing the 1th part of the Spring Series, which consists of three parts, I used an example that showed how to inject the application's dependencies through the Spring IOC container (rather than building them in).


I use the use case as a starting point for opening an online credit account. For this implementation, opening a credit account requires the user to interact with the following services:


☆ Credit rating Service, check the 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 necessary).


☆ Email service to send email to users about the status of the credit card.


Three interfaces


For this example, I assume that the service already exists, and ideally the situation is to integrate them in a loosely coupled fashion. The following list shows the application interfaces for 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 that contains client 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 necessary) and inserts the user's credit card information. The credit link interface is a remote service, and its query is done 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);













Copyright notice: I feel like I'm doing a good job. I hope you can move your mouse and keyboard for me to order a praise or give me a comment, under the Grateful!_____________________________________________________ __ Welcome reprint, in the hope that you reprint at the same time, add the original address, thank you with

Hibernate face questions and Answers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.