SpringMvc+Mybatis 框架搭建

时间:2021-06-21 00:32:42

本文承接上一篇【idea使用maven搭建springmvc

开篇:在main/resources下新建dbconfig.properties、spring.xml、spring-mybatis.xml,内容如下:

SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/dangdb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=root
dbconfig.properties
SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 引入dbconfig.properties属性文件 -->
    <context:property-placeholder location="classpath:dbconfig.properties" />
    <!-- 自动扫描(自动注入),扫描me.gacl.service这个包以及它的子包的所有使用@Service注解标注的类 -->
    <context:component-scan base-package="com.dang.service" />
</beans>
spring.xml
SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

    <!-- JNDI方式配置数据源 -->
    <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->
    <!-- ========================================配置数据源========================================= -->
    <!-- 配置数据源,使用的是alibaba的Druid(德鲁伊)数据源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="20" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />
        <!--
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="33" />
        -->
        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- 监控数据库 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>

    <!-- ========================================分隔线========================================= -->

    <!-- ========================================针对myBatis的配置项============================== -->
    <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描com/dang/mapping/目录下的所有SQL映射的xml文件, 省掉Configuration.xml里的手工配置
        value="classpath:com/dang/mapping/*.xml"指的是classpath(类路径)下me.gacl.mapping包中的所有xml文件
        UserMapper.xml位于com/dang.mapping包下,这样UserMapper.xml就可以被自动扫描
         -->
        <property name="mapperLocations" value="classpath:com/dang/mapping/*.xml" />
    </bean>
    <!-- 配置扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描com/dang.dao这个包以及它的子包下的所有映射接口类 -->
        <property name="basePackage" value="com.dang.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- ========================================分隔线========================================= -->
    <!-- 配置Spring的事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 注解方式配置事物 -->
    <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

    <!-- 拦截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="append*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="repair" propagation="REQUIRED" />
            <tx:method name="delAndRepair" propagation="REQUIRED" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* com.dang.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    </aop:config>


    <!-- 配置druid监控spring jdbc -->
    <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
    </bean>
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
        <property name="patterns">
            <list>
                <value>com.dang.service.*</value>
            </list>
        </property>
    </bean>
    <aop:config>
        <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
    </aop:config>

</beans>
spring-mybatis.xml

 

1、在com.dang目录下新建文件夹如下图:

SpringMvc+Mybatis 框架搭建

2、根据mybatis-generator工具生成数据表的相关代码和sql映射文件

打开http://mvnrepository.com/ 搜索mybatis-generator-core,这里我选择了最新版的1.3.5

SpringMvc+Mybatis 框架搭建

解压后找到lib目录,把当前使用的mysql jar包放在此目录下,并新建generator.xml 文件,内容如下

SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--targetProject:生成文件存放路径,方便起见在同级目录新建src文件夹,都存放在此文件夹-->
    <!-- 数据库驱动包位置 因放在同级文件夹,可直接写包名-->
    <classPathEntry location="mysql-connector-java-5.1.39.jar" />
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- 数据库链接URL、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/dangdb" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!-- 生成实体类的包名和位置,这里配置将生成的实体类放在com.dang.model这个包下 -->
        <javaModelGenerator targetPackage="com.dang.model" targetProject="src">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- 生成的SQL映射文件包名和位置,这里配置将生成的SQL映射文件放在com.dang.mapping这个包下 -->
        <sqlMapGenerator targetPackage="com.dang.mapping" targetProject="src">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置,这里配置将生成的dao类放在com.dang.model这个包下 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.dang.dao" targetProject="src">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
        <table tableName="sysuser" domainObjectName="SysUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
    </context>
</generatorConfiguration>
generator.xml

生成方法:选中lib文件夹【shift+右键】,选择“在此处打开命令窗口”打开cmd窗口,输入

java -jar mybatis-generator-core-1.3.5.jar -configfile generator.xml –overwrite

SpringMvc+Mybatis 框架搭建

把生成的文件放入项目相应的文件夹

3、在service文件夹下新建SysUserService接口,impl下新建SysUserServiceImpl类

SysUserService内容如下: 

SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
package com.dang.service;

import com.dang.model.SysUser;
import java.util.List;

/**
 * Created by dang on 2017/1/5.
 */

public interface SysUserService {

    /**
     * 添加
     * @param sysUser
     */
    int addSysUser(SysUser sysUser);

    /**
     * 删除
     * @param id
     */
    int deleteBySysUserId(Integer id);

    /**
     * 修改
     * @param sysUser
     */
    int updateBySysUserId(SysUser sysUser);

    /**
     * 根据用户id获取用户
     * @param sysUserId
     * @return
     */
    SysUser getSysUserById(Integer sysUserId);

    List<SysUser> getAll();
}
SysUserService

SysUserServiceImpl内容如下:  

SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
package com.dang.service.impl;

import com.dang.dao.SysUserMapper;
import com.dang.model.SysUser;
import com.dang.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by dang on 2017/1/5.
 */
/**
 * 使用@Service注解将SysUserServiceImpl类标注为一个service
 * service的id是sysUserService
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService{

    /**
     * 使用@Autowired注解标注sysUserMapper变量,
     * 当需要使用SysUserMapper时,Spring就会自动注入SysUserMapper
     */
    @Autowired
    private SysUserMapper sysUserMapper; //注入dao

    @Override
    public int addSysUser(SysUser sysUser) {
       return sysUserMapper.insert(sysUser);
    }

    @Override
    public int deleteBySysUserId(Integer id) {
        return sysUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateBySysUserId(SysUser sysUser) {
        return sysUserMapper.updateByPrimaryKey(sysUser);
    }

    @Override
    public SysUser getSysUserById(Integer sysUserId) {
        return sysUserMapper.selectByPrimaryKey(sysUserId);
    }

    @Override
    public List<SysUser> getAll() {
        return sysUserMapper.getAll();
    }

}
SysUserServiceImpl

ps: getAll()方法因为在生成映射和sql语句时是没有的,要在SysUserMapper.xml文件中添加上去

SpringMvc+Mybatis 框架搭建

并在dao文件夹SysUserMapper接口中加入此项,完整内容如下:

SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
package com.dang.dao;

import com.dang.model.SysUser;

import java.util.List;

/**
 * 各方法名均要对应SysUserMapper.xml中各标签的【id】值
 */
public interface SysUserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(SysUser record);

    int insertSelective(SysUser record);

    SysUser selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(SysUser record);

    int updateByPrimaryKey(SysUser record);

    List<SysUser> getAll();
}
SysUserMapper

4、在controller文件夹添加SysUserController的java文件,内容如下:

SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
package com.dang.controller;

import com.dang.model.SysUser;
import com.dang.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * Created by dang on 2017/1/5.
 */
@Controller
@RequestMapping(value = "sysuser")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(ModelMap modelMap) {
        List<SysUser> list = sysUserService.getAll();
        modelMap.addAttribute("list", list);
        return "sysuser/list";
    }
}
SysUserController

在webapp\WEB-INF\View 文件夹下新建sysuser/list.jsp,内容如下:

SpringMvc+Mybatis 框架搭建SpringMvc+Mybatis 框架搭建
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: dang
  Date: 2017/1/5
  Time: 15:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>list</title>
</head>
<body>
<table>
    <tr>
        <td>ID</td>
        <td>用户名</td>
        <td>密码</td>
    </tr>
    <c:forEach var="list" items="${list}">
        <tr>
            <td>${list.id}</td>
            <td>${list.username}</td>
            <td>${list.userpwd}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>
list.jsp

 

ps:添加、修改的一些操作也大致如此

运行项目,打开 http://localhost:8080/sysuser/list

SpringMvc+Mybatis 框架搭建

运行成功,项目配置完成。

整个项目结构如下:

SpringMvc+Mybatis 框架搭建

 

mybatis-generator下载