Spring MVC Notes - A Simple Example of Spring+MyBatis Composite Development

Posted by novice_php on Wed, 11 Sep 2019 20:04:10 +0200

Original Link: https://my.oschina.net/u/2400661/blog/596236

brief introduction

SSH framework is strong and suitable for large-scale project development.But there is no end to learning, learning more about a framework combination development will add a lot to your own value.
SSM framework is compact and sophisticated, suitable for rapid development of small and medium-sized projects, and simple for beginners.Before building the SM framework, let's start by learning to combine Spring+MyBatis, and then start with a simple example.

Example

Step 1 - Guide

Spring Framework Package and its Dependent Package+MyBatis Framework Package and its Dependent Package+EhCache Package+C3P0 Package+MySql Driver Package

The example package directory is as follows:

The sample project structure is as follows:

Step 2 - Various profiles

SpringMVC configuration file (ApplicationContext.xml)

<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->

    <context:component-scan base-package="cn.pwc" />

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db_pwc" />
        <property name="user" value="pwc" />
        <property name="password" value="123456" />
        <property name="maxPoolSize" value="20" />
        <property name="minPoolSize" value="1" />
        <property name="initialPoolSize" value="3" />
        <property name="maxIdleTime" value="60" />
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="SqlMapConfig.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.pwc.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

    </bean>

</beans>

1. Configure C3P0 connection pool beans and SqlSessionFactory factory class beans
2. The instance uses the Mapper proxy, so you need to configure the bean for MapperScannerConfigurer
3. The bean's basePackage property value is the package of the automatically scanned apper.xml
4. The scanned Mapper automatically instantiates the load, and the bean name of the instance is the first lowercase Mapper interface name, for example, the instance interface is UserMapper.java, and the instantiated bean is named userMapper.

MyBatis configuration file (SqlMapConfig.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="cacheEnabled" value="true"/>
    </settings>
    <mappers>
        <package name="cn.pwc"/>
    </mappers>
</configuration>

Because Spring manages layers, DAO layer configurations, connection pools, and so on, all Spring configurations need to do is write simple global settings and Mapper.xml Autoscan configurations.
Here the global configuration opens the secondary cache, where cacheEnabled is set to true.

MyBatis's Mapper configuration file (UserMapper.xml)

<?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="cn.pwc.dao.UserMapper">
    <cache type="org.mybatis.caches.ehcache.EhcacheCache" />
    <select id="findById" parameterType="int" resultType="cn.pwc.pojo.User">
        SELECT * FROM user WHERE id=#{id}
    </select>
    <select id="findByAge" parameterType="int" resultType="cn.pwc.pojo.User">
        SELECT * FROM user WHERE age=#{age}
    </select>
    <delete id="deleteById" parameterType="int">
        DELETE FROM user WHERE id=#{id}
    </delete>
    <insert id="insert" parameterType="cn.pwc.pojo.User">
        INSERT INTO user(name,age) VALUES(#{name},#{age})
    </insert>
</mapper>

The ORM map Mapper file opens a secondary cache and is designated as EhCache for its management

EhCache configuration file (ehcache.xml)

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <diskStore path="F:\cache_test" />
    <defaultCache eternal="false" maxElementsInMemory="1000" timeToIdleSeconds="20" timeToLiveSeconds="20" overflowToDisk="false" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="20" memoryStoreEvictionPolicy="LRU" />
</ehcache>

It is important to note here that the overflowToDisk property value, if true, inherits the Serializable interface from the cached pojo class.

Log4j configuration file (log4j.properties)

log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n

Step 3 - Testing

The test classes are as follows:

package cn.pwc.test;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.pwc.dao.UserMapper;
import cn.pwc.pojo.User;

public class Test extends SqlSessionDaoSupport{

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserMapper mapper=(UserMapper) context.getBean("userMapper");
        User user = mapper.findById(1);
        System.out.println(user.toString());
        User user2 = mapper.findById(1);
        System.out.println(user2.toString());
        User user3 = mapper.findById(1);
        System.out.println(user3.toString());
        User user4 = mapper.findById(1);
        System.out.println(user4.toString());
        context.close();

    }

}

Reproduced at: https://my.oschina.net/u/2400661/blog/596236

Topics: Mybatis xml Spring log4j