美文网首页我爱编程
Spring Boot集成Mybatis 入门第二篇

Spring Boot集成Mybatis 入门第二篇

作者: Time大王 | 来源:发表于2018-06-10 10:51 被阅读0次

    对于多表多条件的分页查询,spring boot稍微有点欠缺,于是楼主研究一下把mybatis集成进来,这个过程并不复杂。
    接上篇,
    首先,把druid连接池Jar包的引用添加到pom.xml文件里

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.0</version>
    </dependency>
    

    如果你在上篇的搭建中有把mybatis jar包引用路径屏蔽掉的话,在这里也要放开。
    展示一下最终的pom.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <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/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.example</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>demo</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.0</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>
    
    

    jar包引入完后,我们来把配置文件修改一下,把mybatis集成进来到application.yml配置文件里来

    #默认使用配置
    spring:
      profiles:
        active: dev
    
    #公共配置与profiles选择无关
    mybatis:
      typeAliasesPackage: com.example.demo.model
      mapperLocations: classpath:mapper/*.xml
    
    
    ---
    
    #开发配置
    spring:
      profiles: dev
    
      datasource:
        url: jdbc:mysql://localhost:3306/test
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
    

    中间加的两行代码即为mybatis的引用,在这里忍不住要说一下,spring boot的配置方式是真的简单,比SSM简单多了。这样在框架上算是集成完了,接下来添加上其他几种需要的文件,来测试一下。
    用mybatis的一大好处就是实体类,mapper和XML文件可以自动生成,关于mybatis的自动生成,可以参考一下这篇博文http://blog.csdn.net/zhshulin/article/details/23912615

    上面我把我已经生成好的文件贴一下
    UserMapper文件

    package com.example.demo.mapper;
    
    import com.example.demo.model.User;
    import org.springframework.stereotype.Repository;
    
    
    public interface UserMapper {
        int deleteByPrimaryKey(Integer id);
    
        int insert(User record);
    
        int insertSelective(User record);
    
        User selectByPrimaryKey(Integer id);
    
        int updateByPrimaryKeySelective(User record);
    
        int updateByPrimaryKey(User record);
    }
    
    

    UserMapper.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.example.demo.mapper.UserMapper" >
        <resultMap id="BaseResultMap" type="com.example.demo.model.User" >
            <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" />
        </resultMap>
        <sql id="Base_Column_List" >
            id, userName, password, age
        </sql>
        <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
            select
            <include refid="Base_Column_List" />
            from User
            where id = #{id,jdbcType=INTEGER}
        </select>
        <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
            delete from User
            where id = #{id,jdbcType=INTEGER}
        </delete>
        <insert id="insert" parameterType="com.example.demo.model.User" >
            insert into User (id, userName, password,
            age)
            values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
            #{age,jdbcType=INTEGER})
        </insert>
        <insert id="insertSelective" parameterType="com.example.demo.model.User" >
            insert into User
            <trim prefix="(" suffix=")" suffixOverrides="," >
                <if test="id != null" >
                    id,
                </if>
                <if test="userName != null" >
                    userName,
                </if>
                <if test="password != null" >
                    password,
                </if>
                <if test="age != null" >
                    age,
                </if>
            </trim>
            <trim prefix="values (" suffix=")" suffixOverrides="," >
                <if test="id != null" >
                    #{id,jdbcType=INTEGER},
                </if>
                <if test="userName != null" >
                    #{userName,jdbcType=VARCHAR},
                </if>
                <if test="password != null" >
                    #{password,jdbcType=VARCHAR},
                </if>
                <if test="age != null" >
                    #{age,jdbcType=INTEGER},
                </if>
            </trim>
        </insert>
        <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.model.User" >
            update User
            <set >
                <if test="userName != null" >
                    userName = #{userName,jdbcType=VARCHAR},
                </if>
                <if test="password != null" >
                    password = #{password,jdbcType=VARCHAR},
                </if>
                <if test="age != null" >
                    age = #{age,jdbcType=INTEGER},
                </if>
            </set>
            where id = #{id,jdbcType=INTEGER}
        </update>
        <update id="updateByPrimaryKey" parameterType="com.example.demo.model.User" >
            update User
            set userName = #{userName,jdbcType=VARCHAR},
            password = #{password,jdbcType=VARCHAR},
            age = #{age,jdbcType=INTEGER}
            where id = #{id,jdbcType=INTEGER}
        </update>
    </mapper>
    

    实体类User

    package com.example.demo.model;
    
    
    public class User {
        private Integer id;
    
        private String userName;
    
        private String password;
    
        private Integer age;
    
        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;
        }
    }
    
    

    启动文件DemoApplication.java修改一下,让其扫描dao层接口。

    package com.example.demo;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
    
    @SpringBootApplication
    @MapperScan("com.example.demo.mapper")
    public class DemoApplication extends SpringBootServletInitializer{
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }
    
    

    UserController

    package com.example.demo.controller;
    
    import com.example.demo.model.User;
    import com.example.demo.service.UserService;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
        @Resource
        private UserService userService;
    
        @RequestMapping("/findUser")
        @ResponseBody
        public User toIndex(HttpServletRequest request, Model model){
            int userId = Integer.parseInt(request.getParameter("id"));
            User user = this.userService.getUserById(userId);
            return user;
        }
    }
    
    

    UserService

    package com.example.demo.service;
    
    import com.example.demo.mapper.UserMapper;
    import com.example.demo.model.User;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    
    
    @Service("userService")
    public class UserService {
        @Resource
        private UserMapper userMapper;
    
    
        public User getUserById(int userId) {
            return userMapper.selectByPrimaryKey(userId);
        }
    
        public boolean addUser(User record){
            boolean result = false;
            try {
                userMapper.insertSelective(record);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return result;
        }
    }
    
    

    打开你的浏览器,访问http://localhost:8080/user/findUser?id=1

    image.png
    这样,就把mybatis集成进来了。

    相关文章

      网友评论

        本文标题:Spring Boot集成Mybatis 入门第二篇

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