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文件已经加载

运行成功:

时间: 2024-10-06 01:23:21

Maven 整合 Spring + MyBatis的相关文章

springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解

@[email protected] 写在最前 之前分享过下面这几篇: mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法) mybatis学习笔记(六) -- maven+spring+mybatis从零开始搭建整合详细过程(下) springmvc学习笔记(一) -- 从零搭建,基础入门 这一篇,在这些练习的基础上,将它们整合在一起! 搭建步骤如下 一.新建maven项目,配置环境,测试是否配置成

使用maven整合spring+springmvc+mybatis

使用maven整合spring+springmvc+mybatis 开发环境: 1. jdk1.8 2. eclipse4.7.0 (Oxygen) 3. mysql 5.7 在pom.xml文件中,引入我们需要的jar包:(按需引入jar包) <properties> <!-- 自定义的spring的版本号 --> <spring.version>4.3.18.RELEASE</spring.version> <!-- 自定义的mybaits的版本号

第一章 maven+springmvc+spring+mybatis+velocity整合

一.ssmm简介 ssmm是当下企业最常用的开发框架架构 maven:管理项目jar包,构建项目 spring:IOC容器,事务管理 springmvc:mvc框架 myBatis:持久层框架 velocity:前端视图模板(相较于jsp,速度非常快,而且不需要占据jvm的永久代内存) 上述这些框架再加上版本控制工具(git).自动化部署工具(jenkins),就组成了当下中大型企业最常用的项目开发部署架构:以上各种框架以后我也会依次做笔记去写的,所以在下边不会做详细介绍.还有,在以下的整合过程

使用Maven 整合Spring和hibernate 适合初级接触的学者

本文,主要介绍Spring 和 hibernate怎么去整合,废话就不多说了,如果不知道spring 和hibernate 是干嘛的,还请去问问度娘哈.下面开始一步一步搭建: 工具: Idea 一.先搭建Spring 1.新建一个maven项目:至于填写项目名称什么的就不一一介绍了 这里我的idea没有自动生成test文件夹,需要大家自己建一下,之后的项目目录如下图所示: 2.下面我贴出项目的Pom文件: <project xmlns="http://maven.apache.org/PO

maven 集成spring ,mybatis

maven工程分模块项目可以模块与模块之间的耦合度降低,各模块之间的联系就没有那么的紧密.通常情况下为了打包方便,建立一个父类的模块.这样打包发布的时候就不用一个个模块打包过去,只有父类的模块手动打包下就可以了, 工程如下图所示: 其中book-parent为父类模块,book-core持久层,book-service为服务层,book-web的可视化层 ,既分别对应mvc中的相应层. 一.book-core 1.添加包支持,pom.xml配置如下: <project xmlns="htt

关于整合spring+mybatis 第二种方式

和第一种方式一样的步骤,不过bean.xml中有些许差异 <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property&g

Maven整合Spring,Spring mvc4.1.6,Hibernate4.3.10项目搭建总结

先上详细的配置文件,在上说明,让大家看完例子后更能清晰的对项目有个认识. 该框架集合的功能模块主要包含以下功能包: guava AspectJ apache common log Spring Hibernate POI jackson oracle quartz 1,web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="

idea+springmvc+spring+mybatis+maven整合返回json数据webapi

首先看一张目录结构图: : 创建步骤: 1.创建maven  webapp工程, 创建完后的目录结构为: 2.添加项目依赖(添加jar包) 需要的jar包: spring-webmvc, spring-test, spring-orm, commons-dbcp, mybatis, mybatis-spring, mysql-connector-java, commons-fileupload, jstl,jackson-core, jackson-databind, jackson-mappe

SpringMvc+Spring+Mybatis+Maven整合

一.建立数据库表,使用generator自动生成相关代码: /* SQLyog Ultimate v11.24 (32 bit) MySQL - 5.1.62-community : Database - mydb ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET