• Maven 整合 Spring + MyBatis


    Maven 整合 Spring + MyBatis 存记录备忘,根据网上搜的孙宇老师的一个视频整理而成

    一、搭建工程

    使用Intellij搭建工程(由于eclipse对maven支持不如Intellij,所以选用Intellij,eclipse搭建工程相对复杂,可以百度相关文章)。

    搭建工程十分简单,建好之后直接进入mybatis 与 Spring整合。

    二、整合Mybatis

    工程搭建好之后已经包含以下jar包,版本为4.1.1.RELEASE

     1         <dependency>
     2             <groupId>org.springframework</groupId>
     3             <artifactId>spring-core</artifactId>
     4             <version>${spring.version}</version>
     5         </dependency>
     6 
     7         <dependency>
     8             <groupId>org.springframework</groupId>
     9             <artifactId>spring-web</artifactId>
    10             <version>${spring.version}</version>
    11         </dependency>
    12 
    13         <dependency>
    14             <groupId>javax.servlet</groupId>
    15             <artifactId>servlet-api</artifactId>
    16             <version>2.5</version>
    17         </dependency>
    18 
    19         <dependency>
    20             <groupId>javax.servlet.jsp</groupId>
    21             <artifactId>jsp-api</artifactId>
    22             <version>2.1</version>
    23             <scope>provided</scope>
    24         </dependency>
    25 
    26         <dependency>
    27             <groupId>org.springframework</groupId>
    28             <artifactId>spring-webmvc</artifactId>
    29             <version>${spring.version}</version>
    30         </dependency>
    31 
    32         <dependency>
    33             <groupId>org.springframework</groupId>
    34             <artifactId>spring-test</artifactId>
    35             <version>${spring.version}</version>
    36             <scope>test</scope>
    37         </dependency>
    38 
    39         <dependency>
    40             <groupId>junit</groupId>
    41             <artifactId>junit</artifactId>
    42             <version>4.11</version>
    43             <scope>test</scope>
    44         </dependency>

    引入mybatis和相应的jar包,缺少的jar包可以在 http://mvnrepository.com/ 网站中查询到。

    例如搜索mybatis的jar包

    可以直接复制到pom文件中。

    mybatis
    mybatis-spring(mybatis整合spring jar包)
    mysql-connector-java (mysql链接jar包)
    druid(阿里数据源jar包)
    aspectjweaver(spring-aop需要用到的jar包)
    spring-tx
    spring-jdbc
            <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.0</version>
            </dependency>
    
            <!-- mysql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.21</version>
            </dependency>
    
            <!-- druid -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.0.18</version>
            </dependency>
    
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.9</version>
            </dependency>
    
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>1.9.13</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>  

    Ctrl + Alt + U 可以查看整个配置,对应排除冲突的jar包

     spring主配置文件,配置自动扫描service包并读取配置文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3        xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
     4 http://www.springframework.org/schema/beans
     5 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     6 http://www.springframework.org/schema/context
     7 http://www.springframework.org/schema/context/spring-context-3.0.xsd
     8 ">
     9 
    10     <!-- 引入属性文件 -->
    11     <context:property-placeholder location="classpath:config.properties"/>
    12 
    13     <!-- 自动扫描(自动注入) -->
    14     <context:component-scan base-package="com.zhy.service"/>
    15 
    16 
    17 </beans>

    配置文件配置数据库相应内容

    validationQuery=SELECT 1
    jdbc_url=jdbc:mysql://localhost:3306/zhy?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
    jdbc_username=root
    jdbc_password=root

    spring与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> -->
    
        <!-- 配置数据源 -->
        <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文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
            <property name="mapperLocations" value="classpath:sql/*.xml"/>
        </bean>
    
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.zhy.dao"/>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        </bean>
    
        <!-- 配置事务管理器 -->
        <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.zhy.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.zhy.service.*</value>
                </list>
            </property>
        </bean>
        <aop:config>
            <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut"></aop:advisor>
        </aop:config>
    
    </beans>

     编写测试用例

    表结构:

    项目结构:

    Users.java

    package com.zhy.bean;
    
    public class Users {
    
        private Integer id;
    
        private String username;
    
        private String password;
    
        private Integer age;
    
        private String email;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        @Override
        public String toString() {
            return "Users{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    ", age=" + age +
                    ", email='" + email + '\'' +
                    '}';
        }
    }

    usersSQL.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="com.zhy.dao.UsersDao" >
        <resultMap id="BaseResultMap" type="com.zhy.bean.Users" >
            <id column="id" property="id" jdbcType="INTEGER" />
            <result column="username" property="username" jdbcType="VARCHAR" />
            <result column="password" property="password" jdbcType="VARCHAR" />
            <result column="age" property="age" jdbcType="INTEGER" />
            <result column="email" property="email" jdbcType="VARCHAR" />
        </resultMap>
        <sql id="Base_Column_List" >
            id, username, password, age, email
        </sql>
        <select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
            select
            <include refid="Base_Column_List" />
            from springmvc_user
            where id = #{id,jdbcType=INTEGER}
        </select>
    </mapper>

    UsersDao.java

    package com.zhy.dao;
    
    import com.zhy.bean.Users;
    
    public interface UsersDao {
    
        Users selectById(Integer id);
    }

    UserService.java

    package com.zhy.service;
    
    import com.zhy.bean.Users;
    
    public interface UserService {
        public Users getUserById(Integer id);
    }

    UserServiceImpl.java

    package com.zhy.service.impl;
    
    import com.zhy.bean.Users;
    import com.zhy.dao.UsersDao;
    import com.zhy.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service("userService")
    public class UserServiceImpl implements UserService{
    
        @Autowired
        private UsersDao usersDao;
    
        @Override
        public Users getUserById(Integer id) {
            return usersDao.selectById(id);
        }
    }

    新建Test类

    package com.zhy.service;
    
    import com.zhy.bean.Users;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:spring/spring.xml", "classpath:spring/spring-mybatis.xml" })
    public class UserServiceTest {
    
        @Autowired
        private UserService userService;
    
        @Test
        public void test() {
            Users user = userService.getUserById(1);
            System.out.println(user.toString());
        }
    }

    运行成功:

    三、整合springMVC

    spring-mvc.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">
    
        <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
        <context:component-scan base-package="com.zhy.controller"/>
    
        
        <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
    </beans>

    UsersController.java

    package com.zhy.controller;
    
    import com.zhy.bean.Users;
    import com.zhy.service.UserService;
    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;
    
    @Controller
    @RequestMapping("/users")
    public class UsersController {
    
        @Autowired
        private UserService userService;
    
        private Users users;
    
        @RequestMapping(method = RequestMethod.GET)
        public String showUsers(ModelMap model){
            users = userService.getUserById(1);
            model.addAttribute("users", users);
            return "showUsers";
        }
    }

    showUsers.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title></title>
    </head>
    <body>
        <p>id:${users.id}</p>
        <p>username:${users.username}</p>
        <p>password:${users.password}</p>
        <p>email:${users.email}</p>
        <p>age:${users.age}</p>
    </body>
    </html>

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
    
        <display-name>keep</display-name>
    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring.xml,classpath:spring/spring-mybatis.xml</param-value>
        </context-param>
    
        <filter>
            <description>字符集过滤器</description>
            <filter-name>encodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <description>字符集编码</description>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <listener>
            <description>spring监听器</description>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <servlet>
            <servlet-name>mvc-dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <description>spring mvc 配置文件</description>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring/spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>mvc-dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!-- 配置session超时时间,单位分钟 -->
        <session-config>
            <session-timeout>15</session-timeout>
        </session-config>
    </web-app>

    运行过程中如果报错,一定仔细查看日志排除问题,一般都是jar包问题或者配置文件配置问题。

    保证spring文件已经加载

    运行成功:

  • 相关阅读:
    git 命令
    减少死锁的几个常用方法
    JFinal SQL in 查询排序
    并发编程中,如何减少上下文切换
    MySql批量更新
    百度编辑器上传图片自定义路径,访问路径动态加载
    百度编辑器不能插入html标签解决方法
    搭建贴吧自动签到服务
    mpv设置CPU软解
    使用Vercel+Github搭建个人博客
  • 原文地址:https://www.cnblogs.com/zhyzyn1314/p/5446742.html
Copyright © 2020-2023  润新知