Spring+MyBatis组合开发简单实例

简介

SSH框架很强大,适合大型项目开发。但学无止境,多学会一门框架组合开发会让自己增值许多。
SSM框架小巧精致,适合中小型项目快速开发,对于新手来说也是简单上手的。在SSM框架搭建之前,我们先学习组合Spring+MyBatis,下面开始简单实例。

实例

第一步——导包

Spring框架包及其依赖包+MyBatis框架包及其依赖包+EhCache架包+C3P0架包+MySql驱动包

本实例架包目录如下:
Spring+MyBatis组合开发简单实例_第1张图片

实例项目结构如下:

第二步——各种配置文件

SpringMVC配置文件(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.配置C3P0连接池bean和SqlSessionFactory工厂类bean
2.该实例使用Mapper代理,因此需配置MapperScannerConfigurer的bean
3.该bean的basePackage属性值为自动扫描的Mapper.xml的所在包
4.扫描到的Mapper会自动实例化装载,实例的bean名为第一个字母为小写的Mapper接口名,例如该实例接口为UserMapper.java,实例化bean名为userMapper。

MyBatis配置文件(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>

Spring+MyBatis组合开发简单实例_第2张图片

因为Spring管理各个层,DAO层配置,连接池等都交给Spring配置,因此MyBatis配置只需写简单全局设置和Mapper.xml自动扫描配置。
这里全局配置打开了二级缓存,即cacheEnabled设置为true。

MyBatis的Mapper配置文件(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>

该ORM映射Mapper文件开启二级缓存,并指定为EhCache交给其管理

EhCache配置文件(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>

这里特别要注意overflowToDisk属性值,若为true,那么缓存的pojo类需继承Serializable接口

Log4j配置文件(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

第三步——测试

测试类如下:

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();

    }

}

你可能感兴趣的:(spring,mvc,mybatis)