SpringBoot2.0系列教程(一)Springboot框架搭建及整合MyBatis

Hello大家好,本章我们搭建项目基础框架结构和整合mybatis;项目所需环境jdk1.8,maven,mysql数据库;开发工具IDEA。另求各路大神指点,感谢

一:通过idea工具构建基础框架

  1.  打开idea,左上角File→New→Project,看到如下图的页面

  2.  点击Next,配置如下图
  3.  点击Next,配置如下图,这里我们选择数据库MySQL和持久层框架MyBatis

  4.  点击Next,选择工作目录,点击Finish,开始构建

 

  5.  创建完成后,项目目录结构如下

DemoApplicttion.java为项目的启动类

application.properties为项目配置文件

pom.xml主要描述了项目的maven坐标,依赖关系,开发者需要遵循的规则,缺陷管理系统,组织和licenses,以及其他所有的项目相关因素,是项目级别的配置文件(说人话:项目所需jar包的管理)

 

二:配置数据库信息

在application.properties文件中添加如下数据库配置

spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false
spring.datasource.username=数据库用户名
spring.datasource.password=数据库密码
spring.datasource.driverClassName=com.mysql.jdbc.Driver

三:创建数据库UserInfo表

 

 

 

 

CREATE TABLE `user_info` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; 

四:创建项目基本目录结构

Model

package com.example.demo.model;

import javax.persistence.Column;
import javax.persistence.Id;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:55
 */
public class UserInfo {

    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * 用户名
     */
    @Column(name = "user_name")
    private String userName;

    private String password;

    public String getId() {
        return id;
    }

    public void setId(String 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;
    }

}

Mapper

<?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.dao.UserInfoMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.model.UserInfo">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    </resultMap>

    <sql id="Base_Column_List">
      id,user_name
    </sql>

    <select id="selectById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user_info
        where id = #{id,jdbcType=VARCHAR}
    </select>

</mapper>

Dao

package com.example.demo.dao;

import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Param;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:54
 */
public interface UserInfoMapper {

    UserInfo selectById(@Param("id") Integer id);
}

Service

package com.example.demo.service;

import com.example.demo.model.UserInfo;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:56
 */
public interface UserInfoService {

    UserInfo selectById(Integer id);

}

ServiceImpl

package com.example.demo.service.impl;

import com.example.demo.dao.UserInfoMapper;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:56
 */
@Service
public class UserInfoServiceImpl implements UserInfoService{

    @Resource
    private UserInfoMapper userInfoMapper;

    public UserInfo selectById(Integer id){
        return userInfoMapper.selectById(id);
    }
}

Controller

package com.example.demo.controller;

import com.example.demo.model.UserInfo;
import com.example.demo.service.UserInfoService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 张瑶
 * @Description:
 * @time 2018/4/18 11:39
 */
@RestController
@RequestMapping("userInfo")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/hello")
    public String hello(){
        return "hello SpringBoot";
    }

    @PostMapping("/selectById")
    public UserInfo selectById(Integer id){
        return userInfoService.selectById(id);
    }
}

Controller中@RestController注解的作用

@RestController是由@Controller和@ResponseBody组成,表示该类是controller和返回的结果为JSON数据,不是页面路径。

 

重点看一下configurer中的MyBatisConfigurer.java

package com.example.demo.core.configurer;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @ClassName: MybatisConfigurer
 * @Description: Mybatis配置
 * @author 张瑶
 * @date 2018年1月20日 下午4:03:46
 *
 */
@Configuration
public class MybatisConfigurer {

   @Bean
   public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
      SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
      factory.setDataSource(dataSource);
      factory.setTypeAliasesPackage("com.example.demo.model");
      // 添加XML目录
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
      return factory.getObject();
   }

   @Bean
   public MapperScannerConfigurer mapperScannerConfigurer() {
      MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
      mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
      mapperScannerConfigurer.setBasePackage("com.example.demo.dao");
      return mapperScannerConfigurer;
   }
}

 

@Configuration表示该文件是一个配置文件

@Bean表示该方法是一个传统xml配置文件中的<Bean id=""></Bean>

其中factory.setTypeAliasesPackage("com.example.demo.model")表示项目中model的存储路径;

factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));表示mapper.xml存储路径;

mapperScannerConfigurer.setBasePackage("com.example.demo.dao");表示dao层的存储路径

五:运行项目

找到DemoApplication,右键,选择run  DemoApplication

控制台打印如下信息即为启动成功

六:测试接口

打开postman(Google浏览器插件,可以去应用商店下载),输入

注意修改自己的ip;出现以下结构数据即访问成功

 

 

 

 

{
    "id": 1,
    "userName": "1"
}

项目地址

码云地址: https://gitee.com/beany/mySpringBoot

GitHub地址: https://github.com/MyBeany/mySpringBoot

 

写文章不易,如对您有帮助,请帮忙点下star

结尾

框架搭建,整合mybatis已完成,后续功能接下来陆续更新,另求各路大神指点,感谢大家。

 

@[TOC](SpringBoot2.0系列教程(一)Springboot框架搭建及整合MyBatis)
# 本章内容
Hello大家好,本章我们搭建项目基础框架结构和整合mybatis;项目所需环境jdk1.8,maven,mysql数据库;开发工具IDEA。另求各路大佬指点,感谢
### 一:通过idea工具构建基础框架
 -  打开idea,左上角File→New→Project,看到如下图的页面:![在这里插入图片描述](https://img-blog.csdnimg.cn/2019040314411022.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDg3MDkxOQ==,size_16,color_FFFFFF,t_70)
 -  点击Next,配置如下图![在这里插入图片描述](https://img-blog.csdnimg.cn/20190403144144612.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDg3MDkxOQ==,size_16,color_FFFFFF,t_70) - 点击Next,配置如下图,这里我们选择数据库MySQL和持久层框架MyBatis![在这里插入图片描述](https://img-blog.csdnimg.cn/20190403144230327.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDg3MDkxOQ==,size_16,color_FFFFFF,t_70) -  点击Next,选择工作目录,点击Finish,开始构建 - 创建完成后,项目目录结构如下 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20190403144257796.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDg3MDkxOQ==,size_16,color_FFFFFF,t_70)
 - DemoApplicttion.java为项目的启动类。  -  application.properties为项目配置文件  - pom.xml主要描述了项目的maven坐标,依赖关系,开发者需要遵循的规则,缺陷管理系统,组织和licenses,以及其他所有的项目相关因素,是项目级别的配置文件(说人话:项目所需jar包的管理)
### 二:配置数据库信息在application.properties文件中添加如下数据库配置
```spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=falsespring.datasource.username=数据库用户名spring.datasource.password=数据库密码spring.datasource.driverClassName=com.mysql.jdbc.Driver```### 三:创建数据库UserInfo表
```CREATE TABLE `user_info` (  `id` int(32) NOT NULL AUTO_INCREMENT,  `user_name` varchar(255) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; ```### 四: 创建项目基本目录结构![在这里插入图片描述](https://img-blog.csdnimg.cn/20190403144555114.png)Model```    package com.example.demo.model;        import javax.persistence.Column;    import javax.persistence.Id;        /**     * @author 张瑶     * @Description:     * @time 2018/4/18 11:55     */    public class UserInfo {            /**         * 主键         */        @Id        private String id;            /**         * 用户名         */        @Column(name = "user_name")        private String userName;            private String password;            public String getId() {            return id;        }            public void setId(String 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;        }        }```
mapper
```<?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.dao.UserInfoMapper">    <resultMap id="BaseResultMap" type="com.example.demo.model.UserInfo">        <id column="id" jdbcType="INTEGER" property="id"/>        <result column="user_name" jdbcType="VARCHAR" property="userName"/>    </resultMap>
    <sql id="Base_Column_List">      id,user_name    </sql>
    <select id="selectById" parameterType="java.lang.Integer" resultMap="BaseResultMap">        select        <include refid="Base_Column_List"/>        from user_info        where id = #{id,jdbcType=VARCHAR}    </select>
</mapper>```dao
```package com.example.demo.dao;
import com.example.demo.model.UserInfo;import org.apache.ibatis.annotations.Param;
/** * @author 张瑶 * @Description: * @time 2018/4/18 11:54 */public interface UserInfoMapper {
    UserInfo selectById(@Param("id") Integer id);}```Service
```package com.example.demo.service;
import com.example.demo.model.UserInfo;
/** * @author 张瑶 * @Description: * @time 2018/4/18 11:56 */public interface UserInfoService {
    UserInfo selectById(Integer id);
}```ServiceImpl
```package com.example.demo.service.impl;
import com.example.demo.dao.UserInfoMapper;import com.example.demo.model.UserInfo;import com.example.demo.service.UserInfoService;import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/** * @author 张瑶 * @Description: * @time 2018/4/18 11:56 */@Servicepublic class UserInfoServiceImpl implements UserInfoService{
    @Resource    private UserInfoMapper userInfoMapper;
    public UserInfo selectById(Integer id){        return userInfoMapper.selectById(id);    }}```Controller
```package com.example.demo.controller;
import com.example.demo.model.UserInfo;import com.example.demo.service.UserInfoService;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/** * @author 张瑶 * @Description: * @time 2018/4/18 11:39 */@RestController@RequestMapping("userInfo")public class UserInfoController {
    @Resource    private UserInfoService userInfoService;
    @PostMapping("/hello")    public String hello(){        return "hello SpringBoot";    }
    @PostMapping("/selectById")    public UserInfo selectById(Integer id){        return userInfoService.selectById(id);    }}```Controller中@RestController注解的作用:@RestController是由@Controller和@ResponseBody组成,表示该类是controller和返回的结果为JSON数据,不是页面路径。

重点看一下configurer中的MyBatisConfigurer.java
```package com.example.demo.core.configurer;
import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.SqlSessionFactoryBean;import org.mybatis.spring.mapper.MapperScannerConfigurer;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
/** * @ClassName: MybatisConfigurer * @Description: Mybatis配置 * @author 张瑶 * @date 2018年1月20日 下午4:03:46 * */@Configurationpublic class MybatisConfigurer {
   @Bean   public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {      SqlSessionFactoryBean factory = new SqlSessionFactoryBean();      factory.setDataSource(dataSource);      factory.setTypeAliasesPackage("com.example.demo.model");      // 添加XML目录      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();      factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));      return factory.getObject();   }
   @Bean   public MapperScannerConfigurer mapperScannerConfigurer() {      MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();      mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");      mapperScannerConfigurer.setBasePackage("com.example.demo.dao");      return mapperScannerConfigurer;   }}
```
 - @Configuration表示该文件是一个配置文件 - @Bean表示该方法是一个传统xml配置文件中的<Bean id=""></Bean> - 其中factory.setTypeAliasesPackage("com.example.demo.model")表示项目中model的存储路径; - factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));表示mapper.xml存储路径; - mapperScannerConfigurer.setBasePackage("com.example.demo.dao");表示dao层的存储路径
### 五:运行项目找到DemoApplication,右键,选择run  DemoApplication
控制台打印如下信息即为启动成功![在这里插入图片描述](https://img-blog.csdnimg.cn/20190403145059546.png)### 六:接口测试打开postman(Google浏览器插件,可以去应用商店下载),输入![在这里插入图片描述](https://img-blog.csdnimg.cn/20190403145212198.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDg3MDkxOQ==,size_16,color_FFFFFF,t_70)注意修改自己的ip;出现以下结构数据即访问成功
```{    "id": 1,    "userName": "1"}```
## 项目地址码云地址: https://gitee.com/beany/mySpringBoot
GitHub地址: https://github.com/MyBeany/mySpringBoot
**写文章不易,如对您有帮助,请帮忙点下star**
## 结尾框架搭建,整合mybatis已完成,后续功能接下来陆续更新。另求各路大神指点,感谢大家。

posted @ 2019-04-03 16:03  mr_初晨  阅读(591)  评论(0编辑  收藏  举报