美文网首页
Spring MVC + Mybaties 集成

Spring MVC + Mybaties 集成

作者: Impact | 来源:发表于2017-07-03 16:55 被阅读0次

    环境和工具

    1. Java版本:
    java version "1.7.0_80"
    Java(TM) SE Runtime Environment (build 1.7.0_80-b15)
    Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode)
    
    1. Maven版本:
    Apache Maven 3.1.1 (0728685237757ffbf44136acec0402957f723d9a; 2013-09-12+0800)
    Maven home: D:\maven3\bin\..
    Java version: 1.7.0_80, vendor: Oracle Corporation
    Java home: D:\Java\jdk1.7.0_80\jre
    Default locale: zh_CN, platform encoding: GBK
    OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"
    
    1. Eclipse版本:
    Version: Mars.2 Release (4.5.2)
    Build id: 20160218-0600
    

    创建maven web项目

    项目创建和目录

    利用Eclipse创建一个Maven project,在Select an Archetype时,选择maven-archetype-webapp,填好groupId和artifactId,完成创建后查看项目。如果项目报错,根据提示修改jre并添加tomcat的library。

    Maven项目的目录说明

    目录 说明
    src/main/java Application/Library sources(源代码)
    src/main/resources Application/Library resources(资源文件)
    src/main/filters Resource filter files
    src/main/webapp Web application sources(html、js等文件)
    src/test/java Test sources
    src/test/resources Test resources
    src/test/filters Test resource filter files
    src/it Integration Tests (primarily for plugins)
    src/assembly Assembly descriptors
    src/site Site
    LICENSE.txt Project's license
    NOTICE.txt Notices and attributions required by libraries that the project depends on
    README.txt Project's readme

    项目结构和代码

    主要结构和配置文件:

    
    modele.com.base
    --controller
    --dao
    --entity
    --service
        --impl
        
    src/main/resources
    --/spring-mvc.xml
    --/spring-mybatise.xml
    --/config/config.properties
    --/mapper/*.xml
    
    

    下面是配置文件的内容,文章的最后贴上测试代码。

    修改配置文件

    pom.xml

    主要是添加Spring和Mybaties等依赖。

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.project</groupId>
      <artifactId>model</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>model Maven Webapp</name>
      <url>http://maven.apache.org</url>
      
        <properties>
        
            <!-- junit -->
            <junit.version>4.11</junit.version>
        
            <!-- spring -->
            <spring.version>4.0.8.RELEASE</spring.version>
            
            <!-- jdbc driver setting -->
            <mysql.driver.version>5.1.30</mysql.driver.version>
            <!-- mybaties -->
            <mybatis.version>3.2.8</mybatis.version>
            <mybatis-spring.version>1.2.2</mybatis-spring.version>
            
            <!-- druid  -->
            <druid.version>1.0.11</druid.version>
    
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
                <type>jar</type>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.1</version>
                <scope>provided</scope>
            </dependency>
    
            <!-- spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            
            <!-- jdbc driver -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.driver.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis-spring.version}</version>
            </dependency>
        
            <!-- connection pool -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
        
            <!-- dataSource -->
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>1.4</version>
            </dependency>
        
            <dependency>
                <groupId>commons-pool</groupId>
                <artifactId>commons-pool</artifactId>
                <version>1.6</version>
            </dependency>
        
        </dependencies>
        
      <build>
        <finalName>model</finalName>
      </build>
    </project>
    
    

    web.xml

    Path:src/main/webapp/WEB-INF/web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0" 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">
    
        <display-name>Archetype Created Web Application</display-name>
    
        <filter>
            <filter-name>encodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <async-supported>true</async-supported>
            <init-param>
                <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>
     
        <!-- Spring MVC servlet -->
        <servlet>
            <servlet-name>SpringMVC</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
            <async-supported>true</async-supported>
        </servlet>
        
        <servlet-mapping>
            <servlet-name>SpringMVC</servlet-name>
            <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        
        <welcome-file-list>
            <welcome-file>/index.jsp</welcome-file>
        </welcome-file-list>  
        
    </web-app>
    
    

    config.properties

    注意不要有空格。

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
    username=root
    password=root
    #\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570  
    initialSize=0  
    #\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570  
    maxActive=20  
    #\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2  
    maxIdle=20  
    #\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2  
    minIdle=1  
    #\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4  
    maxWait=60000 
    

    spring-mvc.xml

    Path:src/main/resources/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"
        xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
        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 
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx.xsd
              http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- 配置扫描的包 -->
        <context:component-scan base-package="model.com.base" />
    
        <!-- 注册HandlerMapper、HandlerAdapter两个映射类 -->
        <mvc:annotation-driven />
    
        <!-- 访问静态资源 -->
        <mvc:default-servlet-handler />
        
        <!-- 引入配置文件 -->
        <import resource="spring-mybatise.xml" />
        
        <!-- 视图解析器 -->
        <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/view/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
    
    </beans>
    

    spring-mybatise.xml

    Path: src\main\resources\spring-mybatise.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:p="http://www.springframework.org/schema/p"  
        xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        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    
                            http://www.springframework.org/schema/mvc    
                            http://www.springframework.org/schema/mvc/spring-mvc.xsd">  
        <!-- 引入配置文件 -->  
        <bean id="propertyConfigurer"  
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
            <property name="location" value="classpath:config/config.properties" />  
        </bean>  
      
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
            destroy-method="close">  
            <property name="driverClassName" value="${driver}" />  
            <property name="url" value="${url}" />  
            <property name="username" value="${username}" />  
            <property name="password" value="${password}" />  
            <!-- 初始化连接大小 -->  
            <property name="initialSize" value="${initialSize}"></property>  
            <!-- 连接池最大数量 -->  
            <property name="maxActive" value="${maxActive}"></property>  
            <!-- 连接池最大空闲 -->  
            <property name="maxIdle" value="${maxIdle}"></property>  
            <!-- 连接池最小空闲 -->  
            <property name="minIdle" value="${minIdle}"></property>  
            <!-- 获取连接最大等待时间 -->  
            <property name="maxWait" value="${maxWait}"></property>  
        </bean>  
      
        <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
            <property name="dataSource" ref="dataSource" />  
            <!-- 自动扫描mapping.xml文件 -->  
            <property name="mapperLocations" value="classpath:mapper/*.xml"></property>  
        </bean>  
      
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
            <property name="annotationClass" value="org.springframework.stereotype.Repository" />
            <property name="basePackage" value="model.com.*.dao" />
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
        </bean>  
      
        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
        <bean id="transactionManager"  
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
            <property name="dataSource" ref="dataSource" />  
        </bean>  
      
    </beans> 
    

    测试

    实现功能:根据id查询记录的详细信息。

    数据库表:

    CREATE TABLE `user_t` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_name` varchar(40) NOT NULL,
      `password` varchar(255) NOT NULL,
      `age` int(4) NOT NULL,
      PRIMARY KEY (`id`)
    )
    

    测试Entity

    UserEntity.java

    package model.com.base.entity;
    
    public class UserEntity {
        
        private int id;
        private String name;
        private String password;
        private int age;
        
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        
        @Override
        public String toString() {
            
            return "id:"+this.id+",name:"+this.name+",age:"+this.age;
        }
        
    }
    
    

    查询 sql

    UserDao.java

    package model.com.base.dao;
    
    import org.apache.ibatis.annotations.Param;
    import org.springframework.stereotype.Repository;
    
    import model.com.base.entity.UserEntity;
    
    @Repository
    public interface UserDao {
    
        UserEntity selectByPrimaryKey(@Param("id")int userId);
    }
    
    

    user.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="model.com.base.dao.UserDao">
    
        <resultMap type="model.com.base.entity.UserEntity" id="userMap">
            <id property="id" column="id" />
            <result property="name" column="user_name" />
            <result property="password" column="password" />
            <result property="age" column="age" />
        </resultMap>
        
        <select id="selectByPrimaryKey" resultMap="userMap">
            SELECT id,user_name,password,age
            FROM user_t a
            WHERE a.id = #{id}
        </select>
        
    </mapper>
    

    Service

    UserService.java

    package model.com.base.service;
    
    import model.com.base.entity.UserEntity;
    
    public interface UserService {
    
        public UserEntity getUserById(int userId);
    }
    
    

    UserServiceImpl.java

    package model.com.base.service.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import model.com.base.dao.UserDao;
    import model.com.base.entity.UserEntity;
    import model.com.base.service.UserService;
    
    @Service
    public class UserServiceImpl implements UserService{
        
        @Autowired
        private UserDao userDao;
    
        public UserEntity getUserById(int userId) {
            return this.userDao.selectByPrimaryKey(userId);  
        }
    
    }
    

    请求处理

    UserController.java

    package model.com.base.controller;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;
    
    import model.com.base.entity.UserEntity;
    import model.com.base.service.impl.UserServiceImpl;
    
    @Controller
    public class UserController{
    
        @Autowired
        private UserServiceImpl userService;
        
        /**
         * 根据id查询用户信息
         * 
         * @param id
         * @return
         */
        @RequestMapping(value="system/select")
        @ResponseBody
        public String selectDate(@RequestParam("id")int id){
            System.out.println("------------request----------id:"+id);
            
            UserEntity user = userService.getUserById(id);
            
            
            return user.toString();
        }
        
    }
    
    
    

    结果

    浏览器地址栏输入:

    http://localhost:8080/model/system/select?id=1
    

    展示结果:

    id:1,name:test,age:24
    

    相关文章

      网友评论

          本文标题:Spring MVC + Mybaties 集成

          本文链接:https://www.haomeiwen.com/subject/njkzcxtx.html