Java Interview-Framework article (ssh-hibernate or STRUT2)

Source: Internet
Author: User
Tags html form

This blog mainly records the SSH framework of the relevant interview knowledge points and questions

1, hibernate working principle and why use?


    1. Read and parse the configuration file
    2. Read and parse mapping information, create Sessionfactory
    3. Open Sesssion
    4. Create Transaction Transation
    5. Persistent operations
    6. Commit a transaction
    7. Close session
    8. Close Sesstionfactory

Why to use:

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

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

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

Hibernate has a very good performance 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. Hibernate Lazy Load Implementation: a) collection of entity object B) (Collection)

2. Hibernate provides lazy loading of properties

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, and they are all manipulating objects;

All of the tables and classes are mapped together in our program through the Many-to-one, One-to-many, many-to-many in the config file,

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

Hibernate's query methods are commonly divided into three main types: HQL, QBC (named query), and native SQL queries (sqlquery)

1, HQL Query

? HQL (Hibernate query Language) provides a rich and flexible way of querying, and querying using HQL is also the official recommended query method for hibernate.

? HQL is the same syntax structure as SQL statements, so it can be used quickly. Using HQL, you need to use the query object in Hibernate, which specializes in HQL-mode operations.

2. QBC (query by Criteria)

? The Criteria object provides an object-oriented way to query the database. The criteria object needs to be obtained using the session object.

? A Criteria object represents a query to a persisted class.

3, the native SQL query:

1 session.begintransaction (); 2 String sql = "Select Id,username,userpwd from T_user"; 3 List list = session.createsqlquery (SQL). List (); 4  for (Object item:list) {5   object[] rows = (object[]) item; 6   SYSTEM.OUT.PRINTLN ("ID:" + rows[0] + "Username:"7     + rows[1] + "USERPWD:" + rows[2]); 8 }9 session.gettransaction (). commit ();
6. How to optimize hibernate?

Hibernate is a framework based on JDBC, but he has many performance optimization techniques that JDBC cannot match. Several optimization strategies are described below.

1. Using Dynamic-insert and Dynamic-update

Using this property in the class tag, you can set hibernate to generate SQL statements dynamically, instead of generating a preset SQL statement when Hibernate starts.

When it is set to True, hibernate sets new or updated fields, rather than all fields, based on the actual needs.

<class name= "" table= "book" dynamic-insert= "true" dynamic-update= "true" >

2. Lazy Loading

To avoid unnecessary overhead in the associated query, query the database whenever you need to read the database. The load () method of the session is used, and get () is not.

(1) Lazy loading of persistent objects


<class name= "Com.hibernate.Category" table= "Category" lazy= "true" >

The following operation does not output any SQL statements

Category category= (category) Session.load (Category.class, New Integer (1));

Tx.commit ();


The load () method gets not a true persisted object, but rather a proxy object that contains the properties and methods of the target object.

The proxy object only needs to get a reference to the persisted class object and does not need to get all the property values.

To successfully generate a proxy object, hibernate's persisted class must have a public construction method and cannot be declared final.

(2) Lazy loading of collection objects

Status: The most important part of delayed loading can significantly improve performance.


<class name= "Com.hibernate.Category" table= "Category" lazy= "true" >

<set name= "Products" cascade= "Save-update" inverse= "true" lazy= "false" >



The following operation does not query the value of the product table:

Category category= (category) Session.load (Category.class, New Integer (1));

System.out.println (Category.getname ());

Tx.commit ();

Note: After the product collection is set to lazy= ' extra ', calling product size (), contains (), and the IsEmpty () method does not raise unnecessary queries.

(3) Deferred loading of attributes

Some database tables have large data field types (BLOB,CLOB), but they are cumbersome to use and, in most cases, have limited performance.

(4) Delay in loading the offending issue

Use Hibernate.initialize (): Forces the associated object to load before the session closes.

Use open session in view design mode.

3. Fetching Strategies for collection objects

Concept: Refers to the policy that hibernate takes when reading an associated object.

(1) Query fetch (SELECT fetching): First queries the persisted object through one SQL statement, and then queries the associated object through another query statement. After you set this policy, you can still overload the crawl policy with the HQL or criteria object.

(2) subquery fetch (subselect fetching): First queries the persisted object through one SQL statement, and then queries the associated object through another subquery statement.

(3) Link crawl (join fetching): Use an outer JOIN statement to get the current object or related object. Queries that use the HQL statement do not take effect, only valid for other query methods such as Session.get (), Criteria.list ().

(4) Batch fetching: First obtain a primary key or foreign key list through a query, and then use a single statement to get the object. Hibernate queries data in batches based on the values set.

4. Hibernate's "1+n" problem

Scenario 1:

The iterate () method of the Query object gets the query data. When the code first uses the iterate () method, hibernate obtains the ID list value and then fetches the data through the N statement and adds it to the cache.

If the iterate () method of the query object does not always hit the cache data well, it will greatly affect its performance, at which point the list () method can be used, and conversely, if the cache can be hit well, it can improve performance.

Scenario 2:

One-to-many, in the side of the search for n objects, then need to be n objects associated with the collection, so that an original SQL query into a n+1 bar.

Many to one, in the multi-query to get M-object, then also will be the M object corresponding to the 1-party object out, also become m+1.
(1) With lazy loading, query actions occur only when you need to associate an object (access its properties, non-ID fields).
(2) with a level two cache, even if the first query is slow, then the hit cache is very fast.

7. What are the core classes of hibernate, and what are their interrelationships? What are the important ways?

Configuration Interface: Configure Hibernate to create a Sessionfactory object according to its startup hibernate;

Sessionfactory Interface: Initialize hibernate, act as the proxy for the data storage source, create session object, Sessionfactory is thread safe, means that its same instance can be shared by multiple threads applied, is heavyweight, level two cache ; Session Interface: Responsible for saving, updating, deleting, loading and querying objects, is thread insecure, to avoid multiple threads sharing the same Session, is lightweight, first-level cache;

The session is as follows: Save,load,update,delete,

Query q=createquery ("from Customer where Customername=:customername")

BeginTransaction, close, transaction, commit

Transaction interface: Management transaction;

Query and Criteria interfaces: Queries that execute the database.

struts type face question1. How the Struts framework works or processes

Struts is an open-source framework that uses Java Servlet/javaserver pages technology to develop Web applications.

Using struts can develop an application architecture based on the MVC (Model-view-controller) design pattern. Struts has the following main functions:

One. Contains a controller servlet that can send a user's request to the appropriate action object.

Two. JSP free tag library, and provide associated support in the controller servlet to help developers create interactive form applications.

Three. Provides a series of practical objects: XML processing, automatic processing of JavaBeans attributes via Java Reflection APIs, internationalization hints and messages.

For Web applications that use the Struts framework, Actionservlet,actionservlet loads and initializes the configuration information from the Struts-config.xml when the Web app starts.

Store them in a variety of configuration objects, such as storing the action's mapping information in a Actionmapping object.

When Actionservlet receives a customer request, the following process is performed:

    1. Retrieve the actionmapping instance that matches the user request, and if it does not exist, returns the invalid user request path information;

    2. If the Actionform instance does not exist, create a Actionform object and save the form content submitted by the customer;

    3. Decide whether to call Actionform's validate () method according to the configuration information;

    4. If Actionform's validate () method returns null or returns a Actionerrors object that does not contain actionmessage, the form validation is successful;

    5.ActionServlet forwards the request to the action based on the mapping information contained in the Actionmapping instance (if the action instance does not exist, create the action instance first) and then call the action's Excute () method;

    The Excute () method of 6.Action Returns a Actionforward object, and Actionservlet forwards the client request to the JSP component that the Actionforward object points to;

    The JSP component that the 7.ActionForward object points to generates a dynamic Web page that is returned to the customer.

2, struts on the embodiment of MVC

  M: In struts, the model consists of JavaBean and EJB components to implement the business logic portion of the program.

C:actionservlet,requestprocessor and Struts helper classes to implement the controller. Actionservlet is the core controller in Struts Actionservlet transfers control to the appropriate action class based on the configuration in the struts configuration file.

The action class is the proxy for the business, and you can invoke the model component in the action class or write other business logic code to accomplish a specific business.

The views in the V:struts framework are primarily made up of JSP files, where struts tags and custom tags can be used to perform simple processing of data in a model component.

The Actionform Bean is actually a javabean that follows a special convention, in struts Actionform beans can be seen as an intermediate memory between the view and the controller for data transfer.

3, the difference between struts1.2 and struts2.0?

    A, action class:
struts1.2 requires the action class to inherit a base class. struts2.0 action can be a simple Jopo object or (Will) inherit the Actionsupport base class
B, Threading mode
The struts1.2 action is singleton and must be thread-safe because there is only one instance of the action that handles all requests.
The singleton strategy limits what Struts1.2 action can do and is especially careful when developing. The action resource must be thread-safe or synchronous.
struts2.0 Action generates an instance for each request, so there is no thread safety issue.
C, servlet dependency
The struts1.2 action relies on the servlet API because HttpServletRequest and HttpServletResponse are passed to the Execut method when an action is invoked.
the struts2.0 action does not depend on the container, allowing the action to be tested separately from the container. If required, the STRUTS2 action can still access the initial request and response.
However, other elements reduce or eliminate the need for direct access to HttpServletRequest and HttpServletResponse.
D, testability
A major problem in testing the struts1.2 action is that the Execute method exposes the servlet API (which makes the test dependent on the container). One third-party extension: Struts TestCase
A set of struts1.2 simulation objects is provided for testing.
Struts2.0 action can be tested by initializing, setting properties, calling methods, and "Dependency injection", which makes testing easier.

4, how to achieve the internationalization of struts

The following are examples of the two languages (Chinese, English):
1. Add struts support to your project
2. Edit the file to include information to use internationalization, for example: Lable.welcome.china=welcome!!!

3. Create an English resource file applicationresource_en.properites
4. Create temporary Chinese resource file Applicationresource_temp.properites For example: lable.welcom.china= China welcomes you!

5. Encode and convert the temporary Chinese resource file. You can use the MyEclipse plug-in, or you can do it under DOS:
Native2ascii-encoding gb2312
6. Adding struts's bean tag library to the JSP

5, the data validation of struts framework can be divided into several types?

 Form validation (handled by Actionform Bean): If the user submits the form without entering a name in the form, the form validation error will be generated

Business logic validation (handled by action): If the user enters the form with the name "Monster", the business rules for this app do not allow "Monster" to be greeted, so a business logic error will be generated.

6. Briefly describe the form validation process of form Bean

1. When the user submits an HTML form, the Struts framework automatically assembles the form data into the Actionform bean.

2. The struts framework then calls the Actionform Bean's Validate () method for form validation.

3. If the Actionerrors object returned by the Validate () method is null, or does not contain any Actionmessage objects, it means there is no error and data validation is passed.

4. If the actionerrors contains a Actionmessage object, it means that a validation error has occurred, and the struts framework will save the Actionerrors object to the request and forward it to the appropriate view component. The view component displays the error message contained in the Actionerrors object within the request scope through the label, prompting the user to modify the error.

7. Brief description of the role of Actionform Bean  

  1, Actionform Bean is also a kind of javabean, in addition to having some javabean general methods, but also contains some special methods, used to validate the HTML form data and to reset its properties to the default values.

2. The struts framework uses actionform beans to transfer form data between view components and controller components.

3. The struts framework saves the user-entered form data received by the view component in the Actionform bean, passes it to the controller component, and the controller component can Actionform The data in the bean is modified the JSP file uses the struts tag to read the modified Actionform bean information and reset the HTML form.

8. What attributes and child elements are included in the action element in the struts configuration file?

Path property: Specifies the path to request access to the action

Type property: Specifies the full class name of the action

Name property: Specifies the Actionform Bean that needs to be passed to the action

Scope Property: Specifies the storage range of the Actionform bean

Validate property: Specifies whether form validation is performed

Input property: Specifies the forwarding path when the form validation fails.

Element also contains a child element that defines a request-forward path.

9. struts pros and cons


  1. Implement the MVC pattern with a clear structure that allows developers to focus only on the implementation of the business logic.
2. With a rich tag can be used, struts of the tag library (Taglib), if flexible to use, it can greatly improve the development efficiency
3. Page Navigation
Make the system's context clearer. Through a configuration file, you can grasp the connection between the parts of the whole system, which is of great benefit to the later maintenance. This is especially true when another group of developers took over the project.
4. Provide exception processing mechanism.
5. Database Link Pool Management
6. Support i18n
First, to go to the presentation layer, you need to configure the forward, if there are 10 display layer of the JSP, need to configure 10 struts, but also does not include sometimes directories, file changes, need to re-modify forward,

Note that after each configuration modification, the entire project needs to be redeployed, and servers such as Tomcate must restart the server

The action of Struts must be the Thread-safe method, which only allows one instance to handle all requests.

So all the resources that the action uses must be synchronized uniformly, which raises the thread-safety issue.
Third, the test is not convenient. Each of struts's actions is coupled to the web layer so that its tests depend on the Web container and unit tests are difficult to implement. However, there is a junit extension tool that struts testcase can implement for its unit testing.

Iv. types of conversions. The Formbean of struts takes all the data as a string type, which can be converted using the tool commons-beanutils. However, it is converted at the class level, and the type of conversion is not configurable.

It is also very difficult to return the error message to the user when the type is converted.

V. The dependency on the servlet is too strong. Struts must rely on servletrequest and servletresponse when handling action, all of which are not able to get rid of the servlet container.

Vi. front-end expression language aspects. Struts integrates Jstl, so it uses the JSTL expression language primarily to get data. But Jstl's expression language is weak in terms of collection and indexed properties.

Vii. control of action execution is difficult. Struts creates an action, which can be very difficult if you want to control the order in which it is executed. You'll even have to write the servlet again to implement your functional requirements.

Eight, the action to perform before and after the processing. Struts handles action as a class-based hierarchies, which makes it difficult to operate before and after action processing.

Nine, the incident support is not enough. In struts, it is actually a form form that corresponds to an action class (or Dispatchaction), in other words: in struts it is actually a form that can only correspond to one event,

Struts This event mode is a coarse-grained event compared to the application Event,application event and the component event

Java interview-skeleton (ssh-hibernate or Strut2)

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.