在SpringMvc中集成Mybatis


Mybatis的详细功能这里不做描述,只讲怎么将Mybatis集成到SpringMvc里面。通过Mybatis我们可以方便的进行数据交互。

1.添加依赖

首先我们添加Mybatis的依赖,打开pom.xmlproperties添加依赖的版本参数:

    <properties>
        <mybatis.spring.version>1.2.5</mybatis.spring.version>
        <mybatis.generator.version>1.3.2</mybatis.generator.version>
        <mysql.version>5.1.38</mysql.version>
    </properties>

然后在dependencies里面添加如下代码:

        <!--mybatis start-->
        <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>
        <!--mybatis end-->

        <!--mybatis-generator-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>${mybatis.generator.version}</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

其中mybatis-generator是一个自动生成mybatis文件的插件。还需要在plugins里面添加插件的信息:

<!--MBG-->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>${mybatis.generator.version}</version>
    <configuration>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
    </configuration>
   </plugin>

2.配置自动加载ApplicationContext

打开web.xml,修改为:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<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>Hello</display-name>

    <!--ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置applicationContext-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--下面目录下的xml文件会自动加载-->
        <param-value>classpath:spring/*.xml</param-value>
    </context-param>

    <!--配置servlet处理请求-->
    <servlet>
        <servlet-name>Hello</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--自定义servlet配置文件地址-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!--classpath:指向的是resources文件夹-->
            <param-value>classpath:spring/Hello-Servlet.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>Hello</servlet-name>
        <!--/表示任何形式的请求都可以通过,可以设置为.do表示后缀为.do的接口才可以访问-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3.配置Mybatis

resources下面创建mapper文件夹,作为mybatis的mapper文件夹。配置mybatis先把mybatis和mybatis-
generator需要使用到的参数配置到一个单独的文件,然后再调用这个文件的值方便后期修改。

  • a.创建mybatis.propertiesresources文件夹下面创建一个文件mybatis.properties,将数据库和mybatis-generator需要的参数加进去,如下:

    #jdbc
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://192.168.2.199:3306/ming?characterEncoding=utf-8&&useUnicode=true&&zeroDateTimeBehavior=convertToNull
    jdbc.username=lingsir
    jdbc.password=123qwe
    #mybatis-generator的相关配置
    mybatis.targetProject=src/main/java
    mybatis.modelPackage=com.bearever.model.entities
    mybatis.daoMapperPackage=com.bearever.dao
    mybatis.targetMapperProject=src/main/resources
    mybatis.sqlMapperPackage=mapper

  • b.创建mybatis-spring.xml 这个文件的作用是引入mybatis的配置,名字无所谓,只要放入web.xml定义的contextConfigLocation文件夹下面就行了,通过ContextLoaderListener可以自动加载目录下的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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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">
    
    <context:property-placeholder location="classpath:mybatis.properties"/>
    
    <!--jdbc配置-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!-- 引入mybatis configuration的相关配置 -->
        <property name="configLocation" value="classpath:mybatisConfig.xml"/>
    </bean>
    
    <!-- 自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 这里需要注意,必须写入映射文件的目录 -->
        <property name="basePackage" value="com.bearever.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"/>
    
  • c.创建mybatisConfig.xml 在web.xml定义的contextConfigLocation文件夹下面创建mybatisConfig.xml,在开发中会遇到需要切换数据库环境,可以通过environments配置。

4.配置mybatis-generator

通过Mybatis-
Generator自动生成mybatis的mapper等文件,在resources创建generatorConfig.xml文件,如下:

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

    <properties resource="mybatis.properties"/>

    <!--mysql-connector的位置-->
    <classPathEntry
            location="C:\Users\luomi\.m2\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar"/>

    <context id="mybatis" targetRuntime="MyBatis3">
        <!-- 防止生成的代码中有很多注释-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
        </commentGenerator>

        <!--数据库-->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}">
        </jdbcConnection>

        <!--Java类型解析器不应该强制型对象字段BigDecimal的使用,此功能是为了使数据库DECIMAL和NUMERIC列容易处理-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="${mybatis.modelPackage}" targetProject="${mybatis.targetProject}">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="${mybatis.sqlMapperPackage}" targetProject="${mybatis.targetMapperProject}">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="${mybatis.daoMapperPackage}"
                             targetProject="${mybatis.targetProject}">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--生成对应表及类名 ByExample="false" 不自动生成实例代码-->
        <table tableName="tb_user" domainObjectName="User"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"/>

    </context>
</generatorConfiguration>

终端cd到项目目录,执行命令生成mybatis代码和xml,提示BUILD SUCCESS表示配置成功了。

mvn mybatis-generator:generate

在代码文件夹里面,会自动生成UserUserMapper和资源文件夹下面的

5.编写Service

创建UserService接口文件,添加下面的方法:

public interface UserService {
    User findUser(Integer id);
}

实现接口方法,创建UserServiceIml文件,这里需要注意@Service标签,如果不设置value的值会默认将类名首字母小写设置为value,通常我们将他的接口名设置为value。

@Service(value = "userService")
public class UserServiceIml implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUser(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            return new User();
        }
        return user;
    }
}

6.编写Controller

Controller里面增加Service引用,通过UserMapper来操作数据库。

@Controller
public class HelloController {
    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "s", method = RequestMethod.GET)
    public ResponseEntity<User> s(@RequestParam(value = "id", defaultValue = "") String id) {
        if (StringUtils.isEmpty(id)) {
            return new ResponseEntity<>(new User(), HttpStatus.OK);
        }
        Integer uid = Integer.parseInt(id);
        User user = this.userService.findUser(uid);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }
}

7.运行

运行项目,打开http://localhost:8085/jump_war/s?id=1,如果你在数据库里面添加了user的表,并且增加了数据,就会看到如下的页面:
Enjoy It

Search by:GoogleBingBaidu