Complete Works of Java Interview Questions(15)

Complete Works of Java Interview Questions(15)

Baiyu IT haha

141. What does the DetachedCriteria class in Hibernate do?

Answer: The usage of DetachedCriteria and Criteria is basically the same, but Criteria is created by Session's createCriteria() method, which means that Criteria cannot be used without the Session that created it. DetachedCriteria can be created without a Session (using the DetachedCriteria.forClass() method), so it is usually called an offline Criteria, and it is bound to the Session (call its getExecutableCriteria(Session) method) when it needs to perform a query operation. This also means that a DetachedCriteria can be bound to a different Session when needed.

142. What is the function of the mappedBy attribute of the @OneToMany annotation?

Answer: @OneToMany is used to configure one-to-many association mapping, but in general, one-to-many association mapping is maintained by multiple parties, such as students and classes. Class attributes should be added to the student class to maintain students and Class association relationship (in the database, the foreign key class number in the student table maintains the many-to-one relationship between the student table and the class table). If you want to use two-way association, add a container attribute to the class class to store the students, And use the @OneToMany annotation for mapping, at this time the mappedBy attribute is very important. If you use XML for configuration, you can use the inverse="true" setting of the <set> tag to achieve the same effect.

143. What is the difference between using # and $ to write placeholders in MyBatis?

Answer: # Treat the incoming data as a string, and automatically add quotation marks to the incoming data; $ displays the incoming data directly in SQL. Note: Using the $ placeholder may cause SQL injection ***. Do not use $ where you can use #. You should use $ instead of # when writing order by clauses.

144. Explain the role of namespace in MyBatis.

Answer: In large projects, there may be a large number of SQL statements. At this time, it is not easy to assign a unique identifier (ID) to each SQL statement. To solve this problem, in MyBatis, a unique namespace can be set for each mapping file, so that each SQL statement defined in this mapping file becomes an ID defined in this namespace. As long as we can ensure that this ID is unique in each namespace, even if the statement IDs in different mapping files are the same, there will be no conflicts.

145. What does the dynamic SQL in MyBatis mean?

Answer: For some complex queries, we may specify multiple query conditions, but these conditions may or may not exist. For example, when looking for a house in 58 same city, we may specify the area, floor and location to find the house. It is also possible to specify the area, price, house type and location to find the house. At this time, it is necessary to dynamically generate SQL statements according to the conditions specified by the user. If we don't use the persistence layer framework, we may need to assemble the SQL statement ourselves. Fortunately, MyBatis provides dynamic SQL functions to solve this problem. The main elements used to implement dynamic SQL in MyBatis are:


- if 
- choose / when / otherwise 
- trim 
- where 
- set 
- foreach

Below is a snippet of the mapping file.


<select id="foo" parameterType="Blog" resultType="Blog">
        select * from t_blog where 1 = 1
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="content != null">
            and content = #{content}
        </if>
        <if test="owner != null">
            and owner = #{owner}
        </if>
   </select>

Of course, you can also write like the following.


 <select id="foo" parameterType="Blog" resultType="Blog">
        select * from t_blog where 1 = 1 
        <choose>
            <when test="title != null">
                and title = #{title}
            </when>
            <when test="content != null">
                and content = #{content}
            </when>
            <otherwise>
                and owner = "owner1"
            </otherwise>
        </choose>
    </select>

Take a look at the following example again.


<select id="bar" resultType="Blog">
        select * from t_blog where id in
        <foreach collection="array" index="index" 
            item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

146. What are IoC and DI? How is DI implemented?

Answer: IoC is called Inversion of Control, which is the abbreviation of Inversion of Control. DI (Dependency Injection) is called Dependency Injection, which is a simpler interpretation of IoC. Inversion of control is the transfer of the calling rights of objects traditionally directly controlled by program code to the container, and the assembly and management of object components are realized through the container. The so-called "inversion of control" is the transfer of control over component objects, from the program code itself to the external container, and the container creates objects and manages the dependencies between the objects. IoC embodies the Hollywood principle-"Don't call me, we will call you". The basic principle of dependency injection is that application components should not be responsible for finding resources or other dependent cooperative objects. The container should be responsible for configuring the object, and the logic for finding resources should be extracted from the code of the application component and handed over to the container to complete. DI is a more accurate description of IoC, that is, the dependency between components is determined by the container at runtime. To put it vividly, the container dynamically injects a certain dependency into the component.
For example: a class A needs to use methods in interface B, then an association or dependency relationship between class A and interface B needs to be established. The most primitive method is to create an instance of class C that implements interface B in class A , But this method requires developers to maintain the dependency between the two, which means that when the dependency changes, the code needs to be modified and the entire system rebuilt. If you manage these objects and their dependencies through a container, you only need to define the method (constructor or setter method) used to associate interface B in class A, and put the implementation class C of class A and interface B into In the container, the association between the two is realized through the configuration of the container.

Dependency injection can be achieved through setter method injection (setting injection), constructor injection, and interface injection. Spring supports setter injection and constructor injection. Usually, constructor injection is used to inject necessary dependencies. For optional Dependency, setter injection is a better choice. Setter injection requires the class to provide a parameterless constructor or a parameterless static factory method to create objects.

147. What are the scope of Bean in Spring?

Answer: In the early version of Spring, there are only two scopes: singleton and prototype. The former means that the Bean exists as a singleton; the latter means that every time the Bean is called from the container, a new instance will be returned, prototype. Usually translated into prototypes.

Supplement: There is also a prototype mode in the creation mode in the design mode. The prototype mode is also a commonly used mode. For example, to make an interior design software, all the materials are in the toolbox, and every time you take out the toolbox A prototype of a material object, the prototype mode can be realized through object cloning.

In Spring 2.x, three new scopes have been added for WebApplicationContext, namely: request (a new bean is created for each HTTP request), session (the same HttpSession shares the same Bean, and different HttpSessions use different Beans) And globalSession (the same global Session shares a Bean).

Explanation: Both singleton mode and prototype mode are important design patterns. In general, a class with no state or immutable state is suitable for singleton mode. In traditional development, because DAO holds Connection, a non-thread-safe object, singleton mode is not used; but in Spring environment, all DAO class pairs can adopt singleton mode, because Spring uses AOP and ThreadLocal in Java API for non- Thread-safe objects are treated specially.

ThreadLocal provides a new idea for solving the concurrency problem of multithreaded programs. ThreadLocal, as the name implies, is a localized object of thread. When an object working in multiple threads uses ThreadLocal to maintain variables, ThreadLocal allocates an independent variable copy for each thread that uses the variable, so each thread can be changed independently A copy of itself, without affecting the corresponding copies of other threads. From the perspective of the thread, this variable is like a local variable of the thread.
The ThreadLocal class is very simple and easy to use. There are only four methods, and the following three methods can be used:

  • void set(T value): Set the value of the thread local variable of the current thread.
  • T get(): Obtain the value of the thread local variable corresponding to the current thread.
  • void remove(): Delete the value of thread local variable in the current thread.
    How does ThreadLocal maintain an independent copy of variables for each thread? There is a Map in the ThreadLocal class, the key is the thread object, and the value is a copy of the variable corresponding to the thread. It is not difficult to simulate a ThreadLocal class by yourself. The code is as follows:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MyThreadLocal<T> {
    private Map<Thread, T> map = Collections
       .synchronizedMap(new HashMap<Thread, T>());
    public void set(T newValue) {
        map.put(Thread.currentThread(), newValue);
    }
    public T get() {
        return map.get(Thread.currentThread());
    }
    public void remove() {
        map.remove(Thread.currentThread());
    }
}

148. Explain what is called AOP (Aspect Oriented Programming)?

Answer: AOP (Aspect-Oriented Programming) refers to a programming paradigm based on a language construct called an aspect. Aspects are a new modular mechanism used to describe scattered The crosscutting concern in an object, class, or method.

149. How do you understand the concept of "crosscutting attention"?

Answer: "Cross-cutting attention" affects the attention function of the entire application. It is orthogonal to the normal business logic and has no necessary connection, but almost all business logic involves these attention functions. Usually, concerns such as transaction, log, and security are the crosscutting concerns in the application.

150. How do you understand the concepts of Joinpoint, Pointcut, Advice, Introduction, Weaving, and Aspect in AOP?

Answer:
a. Joinpoint: a specific position of program execution (for example, before and after a method is called, after the method throws an exception). A class or a piece of program code has some specific points with boundary properties, and the specific points in these codes are connection points. Spring only supports connection points of methods.
b. Pointcut: If the connection point is equivalent to a record in the data, then the pointcut is equivalent to the query condition, and one pointcut can match multiple connection points. Spring AOP's rule parsing engine is responsible for parsing the query conditions set by the cut point and finding the corresponding connection point.
c. Enhancement (Advice): Enhancement is a piece of program code woven into the connection point of the target class. The enhanced interfaces provided by Spring are all with location names, such as BeforeAdvice, AfterReturningAdvice, ThrowsAdvice, etc. Many materials have translated enhancements into "notifications", which is obviously an unsatisfactory translation, which has puzzled many programmers for a long time.

Note: Advice is translated as "notification" in many domestic written materials, but obviously this translation cannot express its essence. There are a few reading materials that translate this word as "enhanced". This translation is more accurate for Advice Interpretation, we add the crosscutting attention function to the original business logic through AOP. This is an enhancement to the original business logic. This enhancement can be pre-enhancement, post-enhancement, post-return enhancement, and exception throwing. Time enhancement and surrounding enhancement.

d. Introduction (Introduction): Introduction is a special enhancement that adds some attributes and methods to the class. In this way, even if a business class does not originally implement a certain interface, through the introduction function, the implementation logic of the interface can be dynamically added to the business class, so that the business class becomes the implementation class of this interface.
e. Weaving: Weaving is the process of adding enhancements to the specific connection points of the target class. AOP has three weaving methods: ① Compile-time weaving: requires a special Java compilation period (for example, ajc of AspectJ); ②Loading period weaving: require the use of a special class loader to enhance the class when loading the class; ③runtime weaving: generate a proxy for the target class to achieve enhancement at runtime. Spring uses dynamic proxy to implement run-time weaving, while AspectJ uses compile-time weaving and load-time weaving.
f. Aspect: The aspect is composed of tangent points and enhancements (introduction). It includes the definition of the cross-cutting attention function and the definition of the connection point.

Supplement: The proxy mode is one of the most classic patterns among the 23 design patterns proposed by GoF. The proxy mode is a structural mode of objects. It provides a proxy object for an object, and the proxy object controls the reference to the original object. Simply put, the proxy object can perform more responsibilities than the original object. When you need to add cross-cutting attention to the original object, you can use the proxy object of the original object. When we open a Word document of the Office series, if there are illustrations in the document, when the document is just loaded, the illustrations in the document are just a dashed placeholder. When the user actually turns to a page and wants to view the picture, it will To actually load this picture, this is actually the use of the proxy mode. The virtual box that replaces the real picture is a virtual proxy; Hibernate's load method also returns a virtual proxy object, and waits for the user to access the properties of the object before sending it to the database. Issue SQL statements to obtain real objects.

Here is an example of finding a gunman to take the test to demonstrate the use of proxy mode:


/**
 * 参考人员接口
 * @author 骆昊
 *
 */
public interface Candidate {
    /**
     * 答题
     */
    public void answerTheQuestions();
}

/**
 * 懒学生
 * @author 骆昊
 */
public class LazyStudent implements Candidate {
    private String name;        // 姓名
    public LazyStudent(String name) {
        this.name = name;
    }
    @Override
    public void answerTheQuestions() {
        // 懒学生只能写出自己的名字不会答题
        System.out.println("姓名: " + name);
    }
}

/**
 * 枪手
 * @author 骆昊
 */
public class Gunman implements Candidate {
    private Candidate target;   // 被代理对象
    public Gunman(Candidate target) {
        this.target = target;
    }
    @Override
    public void answerTheQuestions() {
        // 枪手要写上代考的学生的姓名
        target.answerTheQuestions();
        // 枪手要帮助懒学生答题并交卷
        System.out.println("奋笔疾书正确答案");
        System.out.println("交卷");
    }
}

public class ProxyTest1 {
    public static void main(String[] args) {
        Candidate c = new Gunman(new LazyStudent("王小二"));
        c.answerTheQuestions();
    }
}

Note: Starting from JDK 1.3, Java provides dynamic proxy technology, allowing developers to create proxy instances of interfaces at runtime, including the Proxy class and the InvocationHandler interface. The following example uses a dynamic proxy to write a proxy for the ArrayList. When adding and deleting elements, the added or deleted elements and the size of the ArrayList are printed on the console:


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
public class ListProxy<T>
 implements InvocationHandler {
    private List<T> target;
    public ListProxy(List<T> target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy,
           Method method, Object[] args)
            throws Throwable {
        Object retVal = null;
        System.out.println("[" + method.getName() + ": "
               + args[0] + "]");
        retVal = method.invoke(target, args);
        System.out.println("[size=" + target.size() + "]");
        return retVal;
    }
}

import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
public class ProxyTest2 {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        Class<?> clazz = list.getClass();
        ListProxy<String> myProxy = new ListProxy<String>(list);
        List<String> newList = (List<String>) 
                Proxy.newProxyInstance(clazz.getClassLoader(), 
                clazz.getInterfaces(), myProxy);
        newList.add("apple");
        newList.add("banana");
        newList.add("orange");
        newList.remove("banana");
    }
}

Note: One limitation of using Java's dynamic proxy is that the proxy class must implement the interface. Although interface-oriented programming is a rule that every excellent Java program knows, the reality is often not satisfactory. For classes that do not implement the interface How to generate a proxy for it? inherit! Inheritance is the most classic way to extend the capabilities of existing code. Although inheritance is often abused by beginners, inheritance is often ignored by advanced programmers. CGLib uses a very low-level bytecode generation technology to generate proxies by creating subclasses for a class. It makes up for the shortcomings of dynamic proxies in Java. Therefore, dynamic proxies and CGLib in Spring are both important means of creating proxies, which are useful for implementing interfaces. The class uses dynamic proxy to generate proxy class for it, and the class that does not implement the interface uses CGLib to create proxy for it through inheritance.

Guess you like

Origin blog.51cto.com/15061944/2593712