SSM learning route with answers (continuous update 2020.5.11)

The self-study route is also a review route. The knowledge learned yesterday belongs to yours, and it may not be yours in 3 days. You will learn the new by reviewing the past.

table of Contents

How to build the first spring program?

Spring core framework package function

What are Spring IOC and DI?

Timing of DI dependency injection

Bean's life cycle

3 ways of dependency injection

ioc initialization process

How to build the first springMvc program?

SpringMvc process


How to build the first Mybatis program?

Mybatis principle

Mybatis first level cache

Mybatis verifies the first level cache

Mybatis configuration order

Mybatis print statement, Mybatis database camel case mapping pojo

Mybatis secondary cache



How to build the first spring program?

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>

applicationContext.xml is placed under resource

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

       <bean id="myBean" class="com.demo.MyBean">
        <property name="id" value="11"></property>
        <property name="name" value="test11"></property>
    </bean>
</beans>

Bean

package com.demo;

public class MyBean {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "MyBean{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

 

Test

@RunWith(SpringJUnit4ClassRunner.class)//speing整合junits
@ContextConfiguration(locations = "classpath:applicationContext.xml")//加载配置文件
public class Test {
    @Resource
    private MyBean myBean;
    @org.junit.Test
    public void test(){
        System.out.println(myBean);
    }
}

You can also leave no comments

import com.demo.MyBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Test {
  
    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        MyBean bean=applicationContext.getBean(MyBean.class);
          System.out.println(bean);
    }
}

Congratulations on the success of the first spring program:

MyBean{id=11, name='test11'}

Spring core framework package function

Spring core: Spring core framework package, which provides IOC container and manages beans.

Spring Context: Provide context.

Spring web: Provide contextual information for web development.

spring-jdbc: Provide database support.

What are Spring IOC and DI?

IOC (Inversion of Control) permission control inversion is a design pattern, a kind of thought, the process of obtaining objects is handed over to the IOC container (traditionally new). And DI (Dependency Injection) is equivalent to a specific implementation of IOC.

The principle of DI is reflection. XML configuration and bean dependency create objects dynamically, so it is called dependency injection.

IOC\AOP principle

ioc: first use reflection to generate an instance, and then actively inject it when calling. aop: dynamic proxy

Timing of DI dependency injection

After the ioc initialization process, the dependency injection process is only triggered when the user asks for a bean from the IOC container for the first time.

If lazy loading lazy-init=true is configured, the bean will be initialized at the first getBean. If it is not configured, the default is false, and it will be initialized directly when the spring container starts (singleton bean).

Bean's life cycle

Instantiate Bean: The Ioc container is instantiated by obtaining the information in the BeanDefinition object, and the instantiated object is wrapped in the BeanWrapper object.
Set object attributes (DI): complete the attribute dependency injection through the attribute setting interface provided by BeanWrapper;
inject the Aware interface ( BeanFactoryAware, you can use this method to obtain other Beans, ApplicationContextAware): Spring will detect whether the object implements the xxxAware interface, and inject the relevant xxxAware instance into the bean
BeanPostProcessor: custom processing (pre-processing and post-processing)
InitializingBean and init-method: execute the initialization method defined by ourselves.
Use
destroy: destroy the bean
 

3 ways of dependency injection

 

 

ioc initialization process

Resource positioning. We generally use external resources to describe Bean objects, so the first step in initializing the IOC container is to locate this external resource.
Loading and parsing of BeanDefinition. Loading is the loading of BeanDefinition. BeanDefinitionReader reads and parses Resource resources, that is, represents the user-defined Bean as the internal data structure of the IOC container: BeanDefinition. A BeanDefinition Map data structure is maintained inside the IOC container, and each one in the configuration file corresponds to a BeanDefinition object.
BeanDefinition registration. Register the BeanDefinition resolved in the second step with the IOC container. This process is implemented through the BeanDefinitionRegistery interface. Inside the IOC container, the BeanDefinition obtained by the second process is actually injected into a HashMap container. The IOC container maintains these BeanDefinitions through this HashMap. One thing to note here is that this process does not complete dependency injection. Dependency registration occurs when the application calls getBean() for the first time to request a Bean from the container. Of course, we can set the preprocessing, that is, set the lazyinit attribute to a certain Bean, then the dependency injection of this Bean will be completed when the container is initialized.

 

How to build the first springMvc program?

SpringMvc process

(1): The user request is sent to DispatcherServlet, and DispatcherServlet calls the HandlerMapping processor mapper;

(2): HandlerMapping finds the corresponding processor according to xml or annotations, generates a processor object and returns it to DispatcherServlet;

(3): DispatcherServlet will call the corresponding HandlerAdapter;

(4): HandlerAdapter calls a specific processor to process the request after adaptation, generates ModelAndView and returns it to DispatcherServlet

(5): DispatcherServlet passes ModelAndView to ViewReslover to parse the generated View and returns it to DispatcherServlet;

(6): DispatcherServlet renders according to View View;

->DispatcherServlet->HandlerMapping->Handler ->DispatcherServlet->HandlerAdapter processing handler->ModelAndView ->DispatcherServlet->ModelAndView->ViewReslover->View ->DispatcherServlet->Return to the customer

How to build the first Mybatis program?

 

 mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!-- 自动驼峰 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
                <property name="url" value="jdbc:oracle:thin:@//127.0.0.1/orcl"/>
                <property name="username" value="scott"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/DeptMapper.xml"/>
    </mappers>

</configuration>

 

public interface DeptMapper {

    Dept selectByPrimaryKey(Integer deptno);

}

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.mapper.DeptMapper">
  <resultMap id="BaseResultMap" type="com.domain.Dept">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="DEPTNO" jdbcType="DECIMAL" property="deptno" />
    <result column="DNAME" jdbcType="VARCHAR" property="dname" />
    <result column="LOC" jdbcType="VARCHAR" property="loc" />
  </resultMap>

  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    <!--
      WARNING - @mbg.generated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select 
    <include refid="Base_Column_List" />
    from SCOTT.DEPT
    where DEPTNO = #{deptno,jdbcType=DECIMAL}
  </select>



</mapper>
public class MybatisTest {
	public static void main(String[] args) throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession  session = sqlSessionFactory.openSession();
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		Dept dept = mapper.selectByPrimaryKey(10);
		System.out.println(dept);
	}
}

Mybatis principle

SqlSessionFactoryBuilder creates SqlSessionFactory, factory mode creates SqlSession, and then generates proxy objects for the interface through dynamic proxy, and maps the SQL execution results in mapper/xml to pojo. 

Mybatis first level cache

The first level cache is turned on by default and cannot be turned off. The first level cache is the sqlsession level cache, in fact, the principle is the map context. Life cycle: Appropriate for commit operations (additions, deletions, and modifications), the first level cache is cleared

Mybatis verifies the first level cache



import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.cache.impl.PerpetualCache;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.snake.mybatis_demo.dao.mapper.DeptMapper;
import com.snake.mybatis_demo.dao.pojo.Dept;

public class MybatisTest {

	public static void main(String[] args) throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession  session = sqlSessionFactory.openSession();
		DeptMapper mapper = session.getMapper(DeptMapper.class);
		Dept dept = mapper.selectByPrimaryKey(10);
		System.out.println(dept);

		DeptMapper mapper1 = session.getMapper(DeptMapper.class);
		Dept dept1 = mapper.selectByPrimaryKey(10);
		System.out.println(dept1);
	}
}

 The result shows that the query statement was printed only once

 

Mybatis configuration order

As long as you know that the Mybatis configuration is sequenced, you don't need to memorize it, you will be prompted when the mouse is moved up.

Mybatis print statement, Mybatis database camel case mapping pojo

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!-- 自动驼峰 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

Mybatis secondary cache

The second-level cache spans Sqlsessions and is a mapper-level cache. Multiple sqlsessions operate on the same mapper and share the second-level cache. Principle: The bottom layer is still HashMap

Similarly, only select will be cached, and additions, deletions, and changes will refresh the cache.

How to achieve:

<setting name="cacheEnabled" value="true"/>    <!-- 二级缓存开启 -->

To enable the second-level cache, the POJO object must also implement the Serializable interface , otherwise an exception will be thrown. 

 

Guess you like

Origin blog.csdn.net/x18094/article/details/105934382