在idea中基于maven的springmvc+mybatis框架的demo及搭建教程

初学spring mvc+mybatis,无奈网上各种资料不全,写此文以备份。

1、在idea中安装mybatis插件

插件下载地址http://download.csdn.net/detail/lanyu19950216/9220631,下载后在idea中插件页选择从磁盘安装插件,安装后重启idea即可。

2、mybatis插件的使用

这里https://www.youtube.com/watch?v=Adlp-XuuKAM这个视频录得挺不错的,可以直接看这个视频。

3、在idea中创建新的项目

如图
newproject.png
然后next,勾上从模版创建项目,然后接续看图
2.png
然后完成

4、创建目录

直接上图3.png

5、创建数据库

看图4.png
id字段设置自增

6、使用mybatis插件生成dao、entity

在resource/mybaits目录上右键,新建mybatis-generator-config,文件名输入mybatis-generator,下面是我的修改后的文件

<?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>

    <!-- Class Driver Path -->
    <classPathEntry location="C:\Users\Ly\.m2\repository\mysql\mysql-connector-java\5.1.37\mysql-connector-java-5.1.37.jar"/>

    <context id="context" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- This property is used to specify whether MBG will include any coments in the generated code -->
            <property name="suppressAllComments" value="false"/>
            <!-- This property is used to specify whether MBG will include the generation timestamp in the generated comments -->
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password=""/>

        <javaTypeResolver>
            <!-- This property is used to specify whether MyBatis Generator should force the use of java.math.BigDecimal
      for DECIMAL and NUMERIC fields, rather than substituting integral types when possible -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="com.lanyus.springmvcmybatis.entity" targetProject="THIS_CONFIGURATION_IS_NOT_REQUIRED">
            <!-- This property is used to select whether MyBatis Generator will generate different Java packages for
      the objects based on the catalog and schema of the introspected table -->
            <property name="enableSubPackages" value="false"/>
            <!-- This property is used to select whether MyBatis Generator adds code to trim the white space from character fields returned from the database -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="mybatis" targetProject="THIS_CONFIGURATION_IS_NOT_REQUIRED">
            <!-- This property is used to select whether MyBatis Generator will generate different Java packages for
      the objects based on the catalog and schema of the introspected table -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <javaClientGenerator targetPackage="com.lanyus.springmvcmybatis.dao" targetProject="THIS_CONFIGURATION_IS_NOT_REQUIRED" type="XMLMAPPER">
            <!-- This property is used to select whether MyBatis Generator will generate different Java packages for
      the objects based on the catalog and schema of the introspected table -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <table tableName="test" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false"/>
    </context>
</generatorConfiguration>

C:UsersLy.m2repositorymysqlmysql-connector-java5.1.37mysql-connector-java-5.1.37.jar这个一看就懂吧
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password=""/>
这里修改jdbc信息
javaModelGenerator targetPackage="com.lanyus.springmvcmybatis.entity" targetProject="THIS_CONFIGURATION_IS_NOT_REQUIRED"
javaClientGenerator targetPackage="com.lanyus.springmvcmybatis.dao" targetProject="THIS_CONFIGURATION_IS_NOT_REQUIRED" type="XMLMAPPER"
这里要修改
sqlMapGenerator targetPackage="mybatis" targetProject="THIS_CONFIGURATION_IS_NOT_REQUIRED"
这句改成和我的一样的
table tableName="test" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
这里的test为表名,如果有多个表就把这句复制多次,并修改

然后选中mybatis-generator.xml,右键,Run As Mybatis Generator,就可以看到在dao、entity、mybatis目录下增加了3个文件,不用管它

7、添加依赖,打开pom.xml,代码如下

<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.springapp</groupId>
    <artifactId>springmvcmybatis</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>springmvcmybatis</name>

    <properties>
        <spring.version>4.1.1.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
            <version>8.0.28</version>
        </dependency>
        
    </dependencies>

    <build>
        <finalName>springmvcmybatis</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*Tests.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

这里我主要是添加了

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.2.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
    <version>8.0.28</version>
</dependency>

其余都是创建的时候自动生成的

8、将mybatis整合到spring mvc中

修改mvc-dispatcher-servlet.xml,这里是我改后的

<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">

    <context:component-scan base-package="com.lanyus.springmvcmybatis.controller"/>
    <context:component-scan base-package="com.lanyus.springmvcmybatis.service"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:/mybatis/*Mapper.xml"/>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"/>
        <constructor-arg index="1" value="BATCH"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.lanyus.springmvcmybatis.dao"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value=""/>
        <property name="maxActive" value="100"/>
        <property name="maxIdle" value="10"/>
        <property name="minIdle" value="0"/>
        <property name="defaultAutoCommit" value="false"/>
    </bean>

</beans>

9、添加service

在service目录右键添加class

package com.lanyus.springmvcmybatis.service;

import com.lanyus.springmvcmybatis.dao.TestMapper;
import com.lanyus.springmvcmybatis.entity.Test;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by Ly on 2015/10/28.
 */
@Service
public class TestService {
    @Resource
    TestMapper dao;
    public String print(int id) {
        Test test = dao.selectByPrimaryKey(id);
        return test.getContent();
    }

    public void updateContent(int id, String content) {
        Test test = dao.selectByPrimaryKey(id);
        test.setContent(content);
        dao.updateByPrimaryKeySelective(test);
    }

    public void newContent(int id, String content) {
        Test test = new Test();
        test.setId(id);
        test.setContent(content);
        dao.insertSelective(test);
    }
}

10、添加controller

修改自动创建的HelloController

package com.lanyus.springmvcmybatis.controller;

import com.lanyus.springmvcmybatis.service.TestService;
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 javax.annotation.Resource;

@Controller
@RequestMapping("/")
public class HelloController {
    @Resource
    TestService service;
    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        model.addAttribute("message", service.print(2));
        return "hello";
    }
}

11、Run
5.png

数据库数据
6.png

demo下载地址:http://download.csdn.net/detail/lanyu19950216/9220917

标签: none

已有 4 条评论

  1. 刚发现idea安装mybatis插件后,无法显示android的layout,禁用mybatis插件后正常

    1. springMVC springMVC

      @ilanyu每次要用springMVC又要去启用

  2. idea学习中 idea学习中

    idea15版的mybatis破解版不能安装了,有没有新的版本,或者其他破解方法

    1. @idea学习中,我也是网上找到的破解版,看新版本有没有大牛去破解了

添加新评论