手记

SpringMVC+Spring+Mybatis+Maven

使用IDE导入maven项目,修改配置,添加依赖

  • 修改web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0"
         metadata-complete="true"></web-app>
  • 添加resources目录以及test目录
    resources目录设置为Resources Root
    test目录建在src目录下设置为test Sources root

配置maven的pom.xml

        <!--测试包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <!-- 项目依赖 -->
        <!--1:日志 Java日志:slf4j,log4j,logback,common-logging
              slf4j 是规范/接口
              日志实现:log4j,logback,common-logging
              使用:sl4f + logback
        -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <!--实现sl4j接口合并-->
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!--2:数据库相关-->
        <!--驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
            <!-- 生命周期为runtime,以为数据库驱动在工作的时候才会用到 -->
            <scope>runtime</scope>
        </dependency>
        <!--连接池-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!--DAO框架:Mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!--mybatis 整合spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--3:Servlet web 相关依赖-->
        <!--标签库-->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!--js标签-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--Json相关依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.4</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!--4:Sping依赖-->
        <!--1)Spring核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <!--2) Spring DAO层依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <!--spring 事务-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <!--3) spring web 先关依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>

        <!--4) spring test-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
  • 数据库


    image.png

  • UserBase.java

public class UserBase {
    private int id;    private String username;    private String password;    private int age;
}
  • dao层接口(UserBaseDao.java)

public interface UserBaseDao {    /*
        增加用户
     */
    int createUser (UserBase userBase);    /*
        更改某id的用户信息
     */
    int updateUserById (int id);    /*
        查询所有用户信息
     */
    List<UserBase> queryAllUser ();    /*
        删除某id的用户
     */
    int delateUserById(int id);
}

MyBatis通过mapper映射机制实现DAO
resources目录创建一个全局的Mybatis配置文件:mybatis-config.xml

  • 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>
        <!--使用jdbc的getGeneratedKeys 获取数据库自增主键值-->
        <setting name="useGeneratedKeys" value="ture"/>
        <!--使用列别名替换列明 默认值true
        select name as title from table
        -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 开启驼峰命名转换:Table(create_time)->Entity(creatTime) -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings></configuration>

使用mapper方式实现Dao接口

接下来要在Mapper中设置namespace来告诉mapper实现哪个Dao,在mapper标签中 加入namespace属性:

<?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="">
    </mapper>

为Dao接口的方法提供SQL语句配置

在mapper文件中一次实现Dao接口中方法的sql,id需要和Dao接口的方法名完全一致,如下:

    <insert id="createUser" parameterType="UserBase">
        insert into user (username,password,age) values (${username},${password},${age})
    </insert>

MyBatis整合Spring

首先在resources目录下创建spring目录用来存放spring配置文件。在这个目录新建一个spring-dao.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"
       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">
    <!--配置整合Mybatis过程-->
    <!--1:配置数据库相关参数-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--2:数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--配置连接池属性-->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!--c3p0私有属性-->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="20"/>
        <!--关闭后不自动commit-->
        <property name="autoCommitOnClose" value="false"/>
        <!--获取链接超时时间-->
        <property name="checkoutTimeout" value="3000"/>
        <!--获取链接失败重试次数-->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>
    <!--3:配置SqlSessionFactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置MyBatis全局配置文件:Mybatis-config.xml-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 扫描entity包 使用别名,可以在value中用分号放入多个位置 -->
        <property name="typeAliasesPackage" value="cn.persistXL.ssm.entity"/>
        <!-- 扫描sql配置文件:mapper文件扫描 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!--4:配置扫描DAO接口包,动态实现DAO接口,并注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory (适应beanname方式后处理,防止在注入之前就使用)-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--给出扫描DAO 接口的包-->
        <property name="basePackage" value="cn.persistXL.ssm.dao"/>
    </bean></beans>
  • 在resource目录下新建jdbc.properties数据库配置文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=truejdbc.username=root
jdbc.password=root

使用JUnit 进行接口测试

进入UserBaseDao类,选中类的名字然后使用快捷键Ctrl+shift+t,选择Create Unit Test,选择JUnit4,然后选中所有接口,创建测试类,在test/java目录下会生成测试类文件,如下图:



image.png


在测试类中需要配置SpringJUnit整合的相关注解,这样JUnit启动的时候会加载Spring,而Spring又整合了Mybatis,从而实现了JUnitSpringMyBatis的整合。
由于之前只实现了createUser接口,我们只对该接口进行单元测试,测试之前不要忘记打开MySQL数据库服务。

package cn.persistXL.ssm.dao;import cn.persistXL.ssm.entity.UserBase;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import javax.annotation.Resource;import static org.junit.Assert.*;/**
 * @author persistXL
 * @data 2018/8/7 19:21
 *//*
 * 配置spring和junit整合,junit启动时加载springIOC容器
 * spring-test,junit
 */@RunWith(SpringJUnit4ClassRunner.class)//告诉junit spring配置文件@ContextConfiguration({"classpath:spring/spring-dao.xml"})public class UserBaseDaoTest {    //注入Dao实现依赖
    @Resource  //注入dao实现
    private UserBaseDao userBaseDao;    @Test
    public void createUser() {
        UserBase userBase = new UserBase();
        userBase.setId(7);
        userBase.setAge(18);
        userBase.setUsername("C罗");
        userBase.setPassword("520cluo");        int insertUser = userBaseDao.createUser(userBase);
        System.out.println(insertUser);
    }    @Test
    public void updateUserById() {
    }    @Test
    public void queryAllUser() {
    }    @Test
    public void delateUserById() {
    }
}



作者:全满
链接:https://www.jianshu.com/p/8ee3beded7df


0人推荐
随时随地看视频
慕课网APP