Ultra-comprehensive Java Face questions (2.1)

Source: Internet
Author: User
Tags message queue relational database table sql injection attack

This part is mainly the open source Java EE framework aspect content, including Hibernate, MyBatis, Spring, Spring mvc and so on, because Struts2 already is the outdated, here does not discuss Struts2 's face question, moreover, This article also provides a simple discussion of enterprise application architectures, large Web site architectures, and application server optimizations, which are believed to be useful for interviews.

126. What is ORM?

A: Object-relational mapping (object-relational Mapping, or ORM) is a technique to solve the mismatch between the object-oriented model of the program and the relational model of the database. Simply put, ORM is to automatically persist objects in a program to a relational database or convert rows from a relational database table to a Java object by using metadata that is mapped between the object and the database (in Java, XML or annotations), essentially converting the data from one form to another.

127. What are the issues to be considered in durable layer design? What is the persistence layer framework you have used?

A: The so-called "persistent" is to save the data to a removable storage device for future use, in short, to save the memory in the relational database, file system, message queue, etc. to provide persistent support devices. The persistence layer is the relatively independent aspect of the system that focuses on achieving data persistence.

The goals of the persistence layer design include:

-Separation of data storage logic, providing an abstract data access interface.

-Data access is decoupled from the underlying implementation, and can be toggled without modifying the code.

-Separation of resource management and scheduling, and implementation of Uniform resource scheduling (e.g. caching mechanism) in the data access layer.

-Data abstraction that provides more object-oriented data manipulation.

The persistence layer Framework is:

-Hibernate

-MyBatis

-TopLink

-Guzz

-Jooq

-Spring Data

-ACTIVEJDBC

128. Is sessionfactory thread-safe in hibernate? is the session thread-safe (can two threads share the same session)?

A: Sessionfactory corresponds to Hibernate's concept of a datastore, which is thread-safe and can be accessed concurrently by multiple threads. Sessionfactory is generally only built when it is started. For applications, it is best to encapsulate sessionfactory in a singleton mode for easy access. The session is a lightweight, non-thread-safe object (a session cannot be shared between threads), which represents a unit of work that interacts with the database. The session is created by Sessionfactory and is closed after the task is completed. The session is the primary interface that the persistence layer service provides externally. The session will delay getting the database connection (that is, it is only available when needed). To avoid creating too many sessions, you can use Threadlocal to bind the session to the current thread so that the same thread will always get the same session. The Sessionfactory getcurrentsession () method in Hibernate 3 can be done.

129. What is the difference between the load and get methods in hibernate session?

Answer: There are three main differences:

① if no records are found that match the criteria, the Get method returns the Null,load method throws an exception.

The ②get method returns the entity class object directly, and the Load method returns the proxy for the entity class object.

③ before Hibernate 3, the Get method only makes data lookups in the first-level cache, if not found

The corresponding data is passed through the level two cache, directly issuing SQL statements to complete the data read; The Load method can fetch data from a level two cache; starting with Hibernate 3, the Get method is no longer write-only to the two-level cache, and it can also access the level two cache.

Description: For the Load () method hibernate believes that the data must exist in the database can be trusted to use the proxy to implement lazy loading, if there is no data to throw an exception, and the Get () method obtained by the data can not exist.

130. What is the Save (), update (), merge (), lock (), Saveorupdate (), and persist () methods of the session respectively? What's the difference?

A: Hibernate has three states: transient (transient), persistent (persistent), and Free State (detached), as shown in the figure in question 135th. Instances of transient states can be persisted by invoking the Save (), persist (), or saveorupdate () method; an instance of a free State can be invoked by calling update (), Saveorupdate (), lock (), or replicate () into a persistent state. Save () and persist () will throw an INSERT statement for SQL, and update () or merge () will throw an UPDATE statement. The difference between save () and update () is that a transient state object is changed to a persistent state, and a Free State object is changed to a persistent state. The merge () method can complete the functionality of the Save () and update () methods, with the intent of merging new states onto existing persisted objects or creating new persisted objects. For the Persist () method, follow the official documentation: the ①persist () method persists an instance of a transient state, but does not guarantee that the identifier is immediately populated into the persisted instance, and that the fill of the identifier may be deferred to the flush time; ②persist () The method guarantees that the persist () method is necessary to encapsulate a long session flow when it is called outside of a transaction, and the ③save () method does not guarantee the ② bar, which returns an identifier, so it executes the INSERT statement immediately. Whether inside or outside the transaction. As for the difference between the lock () method and the update () method, the update () method is to turn an object that has changed out of the tube state into a persistent state, and the lock () method turns an object that has not changed out of the tube state into a persistent state.

131. The process of loading entity object in session is expounded.

A: The steps to load an entity object are:

①session before invoking the database query function, the first level cache through the entity type and the primary key to find, if the first-level cache lookup hit and the data state is legitimate, then return directly;

② if the first level cache is not hit, the next session will be found in the current nonexists record (equivalent to a query blacklist, if duplicate invalid queries can be quickly judged to improve performance), if the same query conditions exist in the nonexists, Then NULL is returned;

③ if the first-level cache query fails, query the level two cache and return directly if the level two cache hits;

④ If none of the previous queries are hit, the SQL statement is issued, and if the query does not find the corresponding record, the query is added to the nonexists of the session to record and return null;

⑤ is resultset based on the mapping configuration and SQL statements, and the corresponding entity objects are created;

⑥ the object into the session (first-level cache) management;

⑦ if there is a corresponding interceptor, execute the OnLoad method of the Interceptor;

⑧ if you turn on and set to use level two cache, the data objects are included in the level two cache;

⑨ returns the data object.

132. What is the difference between the list method and the iterate method of the query interface?

For:

The ①list () method cannot take advantage of a primary cache and a level two cache (write-only to the cache), it can only use query caching on the premise that the query cache is turned on, and the Iterate () method takes full advantage of the cache, and using the iterate () method can reduce performance overhead if the target data is read-only or read frequently.

The ②list () method does not cause n+1 query problems, and the iterate () method may cause n+1 query problems

Description: About n+1 query problem, you can refer to an article on CSDN, "What is n+1 query"

133, hibernate how to realize paging query?

A: For paged queries through hibernate, developers only need to provide HQL statements (call the session's CreateQuery () method) or query conditions (call the session's Createcriteria () method), Sets the number of start rows of the query (the Setfirstresult () method that calls the query or criteria interface) and the maximum number of query rows (the Setmaxresults () method that invokes the query or criteria interface), and call the list () method of the query or criteria interface, Hibernate automatically makes the SQL statement of the Component page query.

134. What is the use of lock mechanism? The pessimistic lock and optimistic locking mechanism of hibernate are briefly described.

A: Some business logic requires exclusive access to data during execution, so there are mechanisms to ensure that data is locked from being modified in the process, which is called locking mechanism.

Hibernate supports two locking mechanisms: pessimistic and optimistic locking. Pessimistic lock, as the name implies pessimistic that in the process of data processing is very likely to have a change of the concurrent transactions (including the system's other transactions or transactions from the external system), so the processed data is set to a locked state. Pessimistic locks must rely on the lock mechanism of the database itself in order to truly guarantee the exclusivity of data access, and the lock mechanism and transaction isolation level of the database are discussed in the Java Plane Question Encyclopedia (above). Optimistic locking, as its name implies, is optimistic about concurrent transactions (that concurrency of data does not occur frequently), and a more permissive locking mechanism to address the severe impact of data access due to pessimistic lock exclusivity on system performance. The most common optimistic lock is implemented by the data version ID, which gets the version number of the data when it is being read, adds 1 to the update data, and then compares the current version number of the corresponding record in the database table, and if the submitted data version number is greater than the current version number of this record in the database, update the data. Otherwise, it is considered that the expired data cannot be updated. Pessimistic locks can be specified by parameters when loading objects from the database through the Get () and load () methods of the session, while optimistic locks can be configured by using the Version field of the entity class to add an integer type to the XML or @version annotations.

Tip: Using optimistic locks adds a version field, which obviously requires extra space to store this version of the field, wasting space, but optimistic locking can make the system more concurrency-saving time. So optimistic locking is also a typical strategy for space-time change.

135. Describe the three states of the entity object and the transformation relationship.

A: The Hibernate object is defined in the latest Hibernate document in four states (originally three states, the interview is basically asked three states), respectively: the Transient state (new, or transient), the persistent state (managed, or Persistent), swim State (detached), and remove state (removed, there are no removed states from the three states defined in the previous Hibernate document), as shown in the previous hibernate document, the removal of the state is considered to be transient.

Transient state: When new is a solid object, the object is in a transient state, that is, the object is just an area of memory that holds temporary data, and if no variable references the object, it is reclaimed by the JVM's garbage collection mechanism. The data stored by this object has nothing to do with the database, unless the transient state object is associated with the database through the session's Save (), Saveorupdate (), persist (), merge () method, and the data is inserted or updated into the database. This object is converted to a persistent state object.

Persistent state: an instance of a persisted object has a corresponding record in the database and has a persistent identity (ID). After a delete operation on a persisted object, the corresponding record in the database is deleted, and the persistent object no longer has a corresponding relationship with the database record, and the persistent object becomes the removal state (which can be considered transient). After the persisted object is modified, it is not synchronized to the database immediately until the database transaction commits.

Free State: When the session has close (), clear (), evict (), or flush (), the entity object changes from the persistent state to the Free State, although the object has persistent and consistent identity values with the database counterpart, but because the object has been purged from the session, The object is not within the persistence management, so it is in a free State (also called off-state). A Free State object is very similar to a temporary state object, except that it also contains persistent identities.

Tip: There is a more detailed explanation of this issue in Hibernate's official documentation.

136. How to understand the lazy loading mechanism of hibernate? In practical applications, how is the contradiction between delayed loading and session closure handled?

A: Lazy loading is not loading the data when it is read, but waiting for it to be loaded when it is used. Hibernate uses the virtual agent mechanism to implement lazy loading, we use the session's load () method to load the data or a one-to-many association map in the case of using lazy loading from the side of the load of a party, get a virtual agent, simply say the return to the user is not the entity itself, Instead, the agent for the entity object. The proxy object will not go to the database to load the data until the user invokes the Getter method. However, loading the data requires a database connection. And when we close the session, the database connection is closed at the same time.

The contradiction between delayed loading and session closing can generally be handled like this:

① off the lazy load feature. This is easier to operate because Hibernate's lazy-loading feature can be configured by mapping files or annotations, but there are obvious flaws in this solution. First, the presence of "no session or session was closed" usually indicates that the primary foreign key association already exists in the system, and that if you remove the lazy load, the cost of each query will become very large.

② gets the data that needs to be queried before the session closes, you can use the tool method Hibernate.isinitialized () to determine if the object is loaded, and if it is not loaded, you can use the Hibernate.initialize () method to load the object.

③ uses interceptors or filters to extend the session's life cycle until the view obtains data. This is what spring integrates with Opensessioninviewfilter and Opensessioninviewinterceptor provided by Hibernate.

137. Give an example of many-to-many associations, and show how to implement many-to-many correlation mappings.

A: For example: Goods and orders, students, and courses are typically many-to-many relationships. Many-to-many associations can be configured on the entity class via @manytomany annotations, or many-to-many associations are configured through the mapping file and tags, but in real-world project development, many-to-many association mappings are converted to two multi-to-one correlation mappings.

138, talk about your understanding of the inheritance map.

A: There are three mapping strategies for inheritance relationships:

① a table for each inheritance structure (table per class hierarchy), regardless of how many subclasses use a single table.

② each subclass a table (table per subclass), the public information is placed in a table, the unique information is placed in a separate table.

③ each specific Class A table (table per concrete Class), how many subclasses have the number of tables.

The first method belongs to the single-table strategy, the advantage is that the query sub-class object without table connection, query speed, suitable for polymorphic queries, the disadvantage is that the table is likely to be large. The latter two methods belong to the multi-table strategy, the advantage is that the data storage is compact, the disadvantage is that the connection query needs to be made, not suitable for polymorphic queries.

139, briefly describe the common optimization strategy of hibernate.

Answer: This question should choose the optimization strategy answer which oneself used, commonly have:

① develop a reasonable caching strategy (level two cache, query cache).

The ② adopts reasonable session management mechanism.

③ use lazy load characteristics as much as possible.

④ set reasonable batch processing parameters.

⑤ if possible, use the UUID as the primary key generator.

⑥ if possible, use the optimistic lock based on the version number instead of the pessimistic lock.

⑦ in the development process, turn on the Hibernate.show_sql option to view the generated SQL to understand the underlying situation, and turn off this option when the development is complete.

⑧ consider the optimization of the database itself, reasonable indexes, appropriate data partitioning strategies, etc. will have a significant increase in the performance of the persistence layer, but these require professional DBA (database administrator) to provide support.

140. Talk about Hibernate's first level cache, level two cache, and query cache.

A: Hibernate session provides a first-level caching function, which is always valid by default, when the application saves persisted entities, modifies persisted entities, the session does not immediately commit this change to the database, but caches it in the current session. The session is closed unless the flush () method that called the session is displayed or by the close () method. With a first-level cache, you can reduce the interaction between the program and the database, thereby improving database access performance.

Sessionfactory level Two cache is global, and all sessions can share this level two cache. However, the level two cache is turned off by default and needs to be displayed on and specify which level of two cache implementation classes you need to use (you can use the implementation provided by a third party). Once the level two cache is turned on and an entity class that requires a level two cache is set, Sessionfactory caches every object of the entity class that has been accessed, unless the cached data exceeds the specified cache space.

Both the first level cache and the level two cache are cached for the entire entity, no normal attributes are cached, and if you want to cache the normal properties, you can use the query cache. The query cache caches HQL or SQL statements and their query results as key-value pairs, and the same query can fetch data directly from the cache. The query cache is also turned off by default and needs to be displayed on.

141, hibernate in Detachedcriteria class is what?

A: The usage of Detachedcriteria and criteria is basically consistent, but the criteria is created by the session's Createcriteria () method, which means leaving the session where it was created, The criteria will not be used. Detachedcriteria does not need a session to create (using the Detachedcriteria.forclass () method), so it is often referred to as offline criteria, When a query operation is required to bind to the session (call its getexecutablecriteria session), it means that a detachedcriteria can be bound to a different session when needed.

142. What is the function of the Mappedby attribute of @OneToMany annotations?

A: @OneToMany is used to configure a one-to-many association mapping, but typically a one-to-many association mapping is maintained by many Parties, such as students and classes, Class attributes should be added to the student class to maintain the relationship between the student and the class (the many-to-one relationship between the student table and the class table is maintained in the database by the foreign-key class number in the Student table), and if you want to use a bidirectional association, add a container attribute to your class class to hold the student, and using @onetomany annotations for mapping, the Mappedby attribute is very important at this point. If you configure using XML, you can use the inverse= "true" setting of the label to achieve the same effect.

143. What is the difference between using # and writing placeholders in MyBatis?

A: #将传入的数据都当成一个字符串, quotation marks are automatically added to the incoming data, and the incoming data is generated directly in SQL. Note: Using the $ placeholder may result in a SQL injection attack, where you can use # without using $, and write the ORDER BY clause with $ instead of #.

144. Explain the role of the MyBatis namespace (namespace).

A: In large projects, there may be a large number of SQL statements, which makes it difficult to make a unique identity (ID) for each SQL statement. To solve this problem, in MyBatis, you can have a unique namespace for each mapping file, so that each SQL statement defined in the mapping file becomes an ID defined in that namespace. As long as we can guarantee that this ID is unique in each namespace, there will be no more conflicts even if the statement IDs in the different mapping files are the same.

145. What does dynamic SQL mean in MyBatis?

A: For some complex queries, we may specify multiple query conditions, but these conditions may or may not exist, for example, in 58 to find a house, we may specify the area, floor and location to find listings, may also specify the area, price, type and location to find listings, At this point, you need to dynamically generate SQL statements based on user-specified conditions. If we do not use the persistence layer framework we may need to assemble our own SQL statements, fortunately MyBatis provides the function of dynamic SQL to solve this problem. The elements used to implement dynamic SQL in MyBatis are:

-If

-Choose/when/otherwise

-Trim

-Where

-Set

-foreach

The following is a fragment of the mapping file.

SELECT * from T_blog where 1 = 1

and title = #{title}

and content = #{content}

and owner = #{owner}

Of course it can be written like the following.

SELECT * from T_blog where 1 = 1

and title = #{title}

and content = #{content}

and owner = "Owner1"

Take a look at the following example.

SELECT * from T_blog where ID in

Item= "Item" open= "(" separator= "," close= ")" >

#{item}

Ultra-comprehensive Java Face questions (2.1)

Related Article

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.