精华内容
参与话题
问答
  • Spring boot Mybatis 整合(完整版)

    万次阅读 多人点赞 2017-08-16 15:59:47
    对Mybatis注解方式有兴趣的,可以查看我的另一篇:Spring boot Mybatis 整合(注解版) 注解方式更加简洁简单,极大程度的提高了开发速度。如果大家需要使用更高的版本比如springboot2.0,请参照我最新的博客...

    对Mybatis注解方式有兴趣的,可以查看我的另一篇:Spring boot Mybatis 整合(注解版) 注解方式更加简洁简单,极大程度的提高了开发速度。如果大家需要使用更高的版本比如springboot2.0,请参照我最新的博客springboot2.0 Mybatis 整合 (springboot2.0版本)

    个人开源项目

    更多干货

    SpringBoot系列目录

    正题

    本项目使用的环境:

    • 开发工具:Intellij IDEA 2017.1.3
    • springboot: 1.5.6
    • jdk:1.8.0_161
    • maven:3.3.9

    额外功能

    • PageHelper 分页插件
    • mybatis generator 自动生成代码插件

    步骤:
    1.创建一个springboot项目:
    这里写图片描述
    2.创建项目的文件结构以及jdk的版本
    这里写图片描述
    3.选择项目所需要的依赖
    这里写图片描述
    这里写图片描述
    然后点击finish

    5.看一下文件的结构:
    这里写图片描述

    6.查看一下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.winter</groupId>
    	<artifactId>springboot-mybatis-demo</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>springboot-mybatis-demo</name>
    	<description>Demo project for Spring Boot</description>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.5.6.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.7</java.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.mybatis.spring.boot</groupId>
    			<artifactId>mybatis-spring-boot-starter</artifactId>
    			<version>1.3.0</version>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-thymeleaf</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<version>5.1.35</version>
    		</dependency>
    		
    	
    		<dependency>
    			<groupId>com.fasterxml.jackson.core</groupId>
    			<artifactId>jackson-core</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>com.fasterxml.jackson.core</groupId>
    			<artifactId>jackson-databind</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>com.fasterxml.jackson.datatype</groupId>
    			<artifactId>jackson-datatype-joda</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>com.fasterxml.jackson.module</groupId>
    			<artifactId>jackson-module-parameter-names</artifactId>
    		</dependency>
    		<!-- 分页插件 -->
    		<dependency>
    			<groupId>com.github.pagehelper</groupId>
    			<artifactId>pagehelper-spring-boot-starter</artifactId>
    			<version>1.1.2</version>
    		</dependency>
    		<!-- alibaba的druid数据库连接池 -->
    		<dependency>
    			<groupId>com.alibaba</groupId>
    			<artifactId>druid-spring-boot-starter</artifactId>
    			<version>1.1.0</version>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    			<!-- mybatis generator 自动生成代码插件 -->
    			<plugin>
    				<groupId>org.mybatis.generator</groupId>
    				<artifactId>mybatis-generator-maven-plugin</artifactId>
    				<version>1.3.2</version>
    				<configuration>
    					<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
    					<overwrite>true</overwrite>
    					<verbose>true</verbose>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    
    
    </project>
    
    

    7.项目不使用application.properties文件 而使用更加简洁的application.yml文件:
    将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,
    文件的内容如下:

    
    server:
      port: 8080
    
    spring:
        datasource:
            name: test
            url: jdbc:mysql://127.0.0.1:3306/depot
            username: root
            password: root
            # 使用druid数据源
            type: com.alibaba.druid.pool.DruidDataSource
            driver-class-name: com.mysql.jdbc.Driver
            filters: stat
            maxActive: 20
            initialSize: 1
            maxWait: 60000
            minIdle: 1
            timeBetweenEvictionRunsMillis: 60000
            minEvictableIdleTimeMillis: 300000
            validationQuery: select 'x'
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            poolPreparedStatements: true
            maxOpenPreparedStatements: 20
    
    ## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
    mybatis:
      mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
      type-aliases-package: com.winter.model  # 注意:对应实体类的路径
    
    #pagehelper分页插件
    pagehelper:
        helperDialect: mysql
        reasonable: true
        supportMethodsArguments: true
        params: count=countSql
    

    8.创建数据库:

    CREATE DATABASE mytest;
    
    CREATE TABLE t_user(
      user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
      user_name VARCHAR(255) NOT NULL ,
      password VARCHAR(255) NOT NULL ,
      phone VARCHAR(255) NOT NULL
    ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
    

    9.使用mybatis generator 自动生成代码:

    • 配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/generator/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>
        <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
        <classPathEntry  location="E:\developer\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/>
        <context id="DB2Tables"  targetRuntime="MyBatis3">
            <commentGenerator>
                <property name="suppressDate" value="true"/>
                <!-- 是否去除自动生成的注释 true:是 : false:否 -->
                <property name="suppressAllComments" value="true"/>
            </commentGenerator>
            <!--数据库链接URL,用户名、密码 -->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/mytest" userId="root" password="root">
            </jdbcConnection>
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
            <!-- 生成模型的包名和位置-->
            <javaModelGenerator targetPackage="com.winter.model" targetProject="src/main/java">
                <property name="enableSubPackages" value="true"/>
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
            <!-- 生成映射文件的包名和位置-->
            <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
                <property name="enableSubPackages" value="true"/>
            </sqlMapGenerator>
            <!-- 生成DAO的包名和位置-->
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.winter.mapper" targetProject="src/main/java">
                <property name="enableSubPackages" value="true"/>
            </javaClientGenerator>
            <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
            <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        </context>
    </generatorConfiguration>
    
    
    
    • 点击run-Edit Configurations

    这里写图片描述

    • 添加配置

    这里写图片描述

    • 运行
      注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,切记
      这里写图片描述

      最后生成的文件以及结构:

    这里写图片描述

    10. 生成的文件

    UserMapper.java

    package com.winter.mapper;
    
    import com.winter.model.User;
    
    public interface UserMapper {
        int deleteByPrimaryKey(Integer userId);
    
        int insert(User record);
    
        int insertSelective(User record);
    
        User selectByPrimaryKey(Integer userId);
    
        int updateByPrimaryKeySelective(User record);
    
        int updateByPrimaryKey(User record);
    	//这个方式我自己加的
    	List<User> selectAllUser();
    }
    

    User.java

    package com.winter.model;
    
    public class User {
        private Integer userId;
    
        private String userName;
    
        private String password;
    
        private String phone;
    
        public Integer getUserId() {
            return userId;
        }
    
        public void setUserId(Integer userId) {
            this.userId = userId;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName == null ? null : userName.trim();
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password == null ? null : password.trim();
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone == null ? null : phone.trim();
        }
    }
    

    对于sql语句这种黄色的背景,真心是看不下去了(解决方案):
    这里写图片描述

    **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.winter.mapper.UserMapper" >
      <resultMap id="BaseResultMap" type="com.winter.model.User" >
        <id column="user_id" property="userId" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="phone" property="phone" jdbcType="VARCHAR" />
      </resultMap>
      <sql id="Base_Column_List" >
        user_id, user_name, password, phone
      </sql>
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from t_user
        where user_id = #{userId,jdbcType=INTEGER}
      </select>
      <!-- 这个方法是我自己加的 -->
      <select id="selectAllUser" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from t_user
      </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from t_user
        where user_id = #{userId,jdbcType=INTEGER}
      </delete>
      <insert id="insert" parameterType="com.winter.model.User" >
        insert into t_user (user_id, user_name, password, 
          phone)
        values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
          #{phone,jdbcType=VARCHAR})
      </insert>
      <insert id="insertSelective" parameterType="com.winter.model.User" >
        insert into t_user
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="userId != null" >
            user_id,
          </if>
          <if test="userName != null" >
            user_name,
          </if>
          <if test="password != null" >
            password,
          </if>
          <if test="phone != null" >
            phone,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="userId != null" >
            #{userId,jdbcType=INTEGER},
          </if>
          <if test="userName != null" >
            #{userName,jdbcType=VARCHAR},
          </if>
          <if test="password != null" >
            #{password,jdbcType=VARCHAR},
          </if>
          <if test="phone != null" >
            #{phone,jdbcType=VARCHAR},
          </if>
        </trim>
      </insert>
      <update id="updateByPrimaryKeySelective" parameterType="com.winter.model.User" >
        update t_user
        <set >
          <if test="userName != null" >
            user_name = #{userName,jdbcType=VARCHAR},
          </if>
          <if test="password != null" >
            password = #{password,jdbcType=VARCHAR},
          </if>
          <if test="phone != null" >
            phone = #{phone,jdbcType=VARCHAR},
          </if>
        </set>
        where user_id = #{userId,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.winter.model.User" >
        update t_user
        set user_name = #{userName,jdbcType=VARCHAR},
          password = #{password,jdbcType=VARCHAR},
          phone = #{phone,jdbcType=VARCHAR}
        where user_id = #{userId,jdbcType=INTEGER}
      </update>
    </mapper>
    

    11.打开类SpringbootMybatisDemoApplication.java,这个是springboot的启动类。我们需要添加点东西:

    package com.winter;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("com.winter.mapper")//将项目中对应的mapper类的路径加进来就可以了
    public class SpringbootMybatisDemoApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
    	}
    }
    
    

    注意:@MapperScan("com.winter.mapper")这个注解非常的关键,这个对应了项目中mapper(dao)所对应的包路径,很多同学就是这里忘了加导致异常的

    12.到这里所有的搭建工作都完成了,接下来就是测试的工作,没使用junit4进行测试:
    首先看一下完成之后的文件的结构:
    这里写图片描述

    现在controller,service层的代码都写好:

    UserController.java

    package com.winter.Controller;
    
    import com.winter.model.User;
    import com.winter.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    /**
     * Created by Administrator on 2017/8/16.
     */
    @Controller
    @RequestMapping(value = "/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @ResponseBody
        @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
        public int addUser(User user){
            return userService.addUser(user);
        }
    
    	@ResponseBody
        @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"})
        public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
    		
            return userService.findAllUser(pageNum,pageSize);
        }
    }
    
    

    UserService.java

    package com.winter.service;
    
    import com.winter.model.User;
    
    import java.util.List;
    
    /**
     * Created by Administrator on 2017/8/16.
     */
    public interface UserService {
    
        int addUser(User user);
    
        List<User> findAllUser(int pageNum, int pageSize);
    }
    
    

    UserServiceImpl.java

    package com.winter.service.impl;
    
    import com.github.pagehelper.PageHelper;
    import com.winter.mapper.UserMapper;
    import com.winter.model.User;
    import com.winter.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * Created by Administrator on 2017/8/16.
     */
    @Service(value = "userService")
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;//这里会报错,但是并不会影响
    
        @Override
        public int addUser(User user) {
    
            return userMapper.insertSelective(user);
        }
    
        /*
        * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
        * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
        * pageNum 开始页数
        * pageSize 每页显示的数据条数
        * */
        @Override
        public List<User> findAllUser(int pageNum, int pageSize) {
            //将参数传给这个方法就可以实现物理分页了,非常简单。
            PageHelper.startPage(pageNum, pageSize);
            return userMapper.selectAllUser();
        }
    }
    
    
    
    

    如果强迫症看不下去那个报错:(解决方法)
    这里写图片描述

    测试我使用了idea一个很用心的功能。
    可以发http请求的插件
    这里写图片描述

    这里写图片描述

    点击左侧的运行按钮就可以发送请求了;
    如果返回值正确 说明你已经搭建成功了!!

    **如果出现mapper注入不了的情况,请检查版本,当前博客的搭建方法只适合1.5.*版本的,如果你的版本是2.0以上的版本,请参照我的另一篇博客的mybatis的配置:springboot2.0整合mybatis **

    如果大家想使用事务控制的话,请参照Spring boot Mybatis 整合(注解版) ,这个里面就有关于事务控制的使用

    源码地址:https://github.com/WinterChenS/springboot-mybatis-demo

    微信公众号:CodeD
    微信公众号

    展开全文
  • SpringBoot整合Mybatis完整详细版

    万次阅读 多人点赞 2018-09-27 10:05:56
    记得刚接触SpringBoot时,大吃一惊,世界上居然还有这么省事的框架,立马感叹:SpringBoot是世界上最好的框架。哈哈! 当初跟着教程练习搭建了一个框架,传送门:spring boot + jpa + bootstrap + thymeleaf 简单的...

    记得刚接触SpringBoot时,大吃一惊,世界上居然还有这么省事的框架,立马感叹:SpringBoot是世界上最好的框架。哈哈!

    当初跟着教程练习搭建了一个框架,传送门:spring boot + jpa + bootstrap + thymeleaf 简单的增删改查Demo

    后来进了新公司,用不到而且忙于任务,今天重温一遍居然有些忘了,看来真是好记性不如烂笔头。于是写下本篇SpringBoot整合Mybatis的文章,做个笔记。

    本章节主要搭建框架,下章节实现登录注册以及拦截器的配置:SpringBoot整合Mybatis完整详细版二:注册、登录、拦截器配置

    本章项目源码下载:springBoot整合mybatis完整详细版

    github地址:https://github.com/wjup/springBoot_Mybatis

    练习完此篇,可下载一小时快速撸出一个短网址生成项目源码来看(欢迎star),也是非常适合入门练手的。

    天也不早了,言归正传,开始


    IDE:idea、DB:mysql

    • 新建一个Spring Initializr项目

    • 创建项目的文件结构以及jdk的版本 

    • 选择项目所需要的依赖

    • 修改项目名,finish完成

    • 来看下建好后的pom
    <?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.5.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-jdbc</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>
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    
    
    </project>
    
    • 修改配置文件

    本文不使用application.properties文件 而使用更加简洁的application.yml文件。将resource文件夹下原有的application.properties文件删除,创建application.yml配置文件(备注:其实SpringBoot底层会把application.yml文件解析为application.properties),本文创建了两个yml文件(application.yml和application-dev.yml),分别来看一下内容

    application.yml

    spring:
      profiles:
        active: dev

    application-dev.yml

    server:
      port: 8080
    
    spring:
      datasource:
        username: root
        password: 1234
        url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
        driver-class-name: com.mysql.jdbc.Driver
    
    mybatis:
      mapper-locations: classpath:mapping/*Mapper.xml
      type-aliases-package: com.example.entity
    
    #showSql
    logging:
      level:
        com:
          example:
            mapper : debug

    两个文件的意思是:

    在项目中配置多套环境的配置方法。
    因为现在一个项目有好多环境,开发环境,测试环境,准生产环境,生产环境,每个环境的参数不同,所以我们就可以把每个环境的参数配置到yml文件中,这样在想用哪个环境的时候只需要在主配置文件中将用的配置文件写上就行如application.yml

    笔记:在Spring Boot中多环境配置文件名需要满足application-{profile}.yml的格式,其中{profile}对应你的环境标识,比如:

    application-dev.yml:开发环境
    application-test.yml:测试环境
    application-prod.yml:生产环境
    至于哪个具体的配置文件会被加载,需要在application.yml文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

    还有配置文件中最好不要有中文注释,会报错。

    解决方法(未测试):spring boot application.yml文件中文注释乱码

    接下来把启动文件移到com.example下,而且springboot的启动类不能放在java目录下!!!必须要个包将它包进去

    否则会报错误:

    Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.

    这个原因值得注意就是因为有时候很难在IDEA中的项目目录认出来这个错误并且还容易扫描不到一些类,传送门:SpringBoot扫描不到controller

                             

    • 然后开始创建实体类实现业务流程

    创建包controller、entity、mapper、service。resources下创建mapping文件夹,用于写sql语句,也可以用注解的方式直接写在mapper文件里。下面直接贴代码

    数据库表结构(之前小项目的表,直接拿来用)

    CREATE TABLE `user` (
      `id` int(32) NOT NULL AUTO_INCREMENT,
      `userName` varchar(32) NOT NULL,
      `passWord` varchar(50) NOT NULL,
      `realName` varchar(32) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

    entity.java

    package com.example.entity;
    
    /**
     * @Author:wjup
     * @Date: 2018/9/26 0026
     * @Time: 14:39
     */
    public class User {
        private Integer id;
        private String userName;
        private String passWord;
        private String realName;
    
        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 String getRealName() {
            return realName;
        }
    
        public void setRealName(String realName) {
            this.realName = realName;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", userName='" + userName + '\'' +
                    ", passWord='" + passWord + '\'' +
                    ", realName='" + realName + '\'' +
                    '}';
        }
    }
    

    UserController.java

    package com.example.controller;
    
    import com.example.entity.User;
    import com.example.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @Author:wjup
     * @Date: 2018/9/26 0026
     * @Time: 14:42
     */
    
    @RestController
    @RequestMapping("/testBoot")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @RequestMapping("getUser/{id}")
        public String GetUser(@PathVariable int id){
            return userService.Sel(id).toString();
        }
    }
    

    UserService.java

    package com.example.service;
    
    import com.example.entity.User;
    import com.example.mapper.UserMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    /**
     * @Author:wjup
     * @Date: 2018/9/26 0026
     * @Time: 15:23
     */
    @Service
    public class UserService {
        @Autowired
        UserMapper userMapper;
        public User Sel(int id){
            return userMapper.Sel(id);
        }
    }
    

    UserMapper.java

    package com.example.mapper;
    
    import com.example.entity.User;
    import org.apache.ibatis.annotations.Select;
    import org.springframework.stereotype.Repository;
    
    /**
     * @Author:wjup
     * @Date: 2018/9/26 0026
     * @Time: 15:20
     */
    @Repository
    public interface UserMapper {
    
        User Sel(int id);
    }
    

    UserMapping.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.mapper.UserMapper">
    
        <resultMap id="BaseResultMap" type="com.example.entity.User">
            <result column="id" jdbcType="INTEGER" property="id" />
            <result column="userName" jdbcType="VARCHAR" property="userName" />
            <result column="passWord" jdbcType="VARCHAR" property="passWord" />
            <result column="realName" jdbcType="VARCHAR" property="realName" />
        </resultMap>
    
        <select id="Sel" resultType="com.example.entity.User">
            select * from user where id = #{id}
        </select>
    
    </mapper>
    
    • 最终框架结构

    • 完成以上,下面在启动类里加上注解用于给出需要扫描的mapper文件路径@MapperScan("com.example.mapper") 
    package com.example;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @MapperScan("com.example.mapper") //扫描的mapper
    @SpringBootApplication
    public class DemoApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(DemoApplication.class, args);
    	}
    }
    

    测试成功,就这样基本框架就搭建成功了

    • 最后给个番外篇如何更改启动时显示的字符拼成的字母,就是更改下图标红框的地方

    其实很好改,只需要在resources下新建一个txt文件就可以,命名为banner.txt,那这种字符该怎么拼出来呢,下面推荐一个网址,有这种工具,链接传送门:字母转字符。如下:

    直接输入要生成的字母,系统会自动转换,然后复制下面转换好的字符到新建的banner.txt文件中,重新启动项目就可以了。


    ---路漫漫其修远兮,吾将上下而求索

     

     

    展开全文
  • SSM整合进阶项目实战-个人博客系统

    千人学习 2018-08-14 23:41:32
    "SSM整合进阶项目实战-个人博客系统开发",属于中级课程,适合于具备了一定java基础以及Spring,SpringMVC跟Mybatis核心框架的基础要点。本课程将更深入的基于SSM整合更多的第三方框架并实现一套比较完整的个人博客...
  • springboot整合kafka实现logback收集日志

    万次阅读 2018-06-25 19:38:53
    springboot中实现logback收集日志输出到kafka 异常容错机制,如果kafka服务宕机,输出到本地文件,可用其他方式重新加载local中的数据记录; 效率比对下:也可以尝试直接用kafka客户端写入到kafka中,手动针对异常做容错...

    springboot实现logback收集日志输出到kafka

    异常容错机制,如果kafka服务宕机,输出到本地文件,可用其他方式重新加载local中的数据记录;

    效率比对下:也可以尝试直接用kafka客户端写入到kafka中,手动针对异常做容错(如,写入文件)

    • 1.pom依赖
    • 2.logback.xml配置
    • 3.自定义KafkaAppender
    • 4.测试代码

    1.kafka相关pom依赖:(0.10.1.1版本)

    <dependency>
    	<groupId>org.apache.kafka</groupId>
    	<artifactId>kafka-clients</artifactId>
    	<version>${kafka.client.version}</version>
    	<scope>compile</scope>
    	<exclusions>
    		<exclusion>
    			<artifactId>slf4j-api</artifactId>
    			<groupId>org.slf4j</groupId>
    		</exclusion>
    	</exclusions>
    </dependency>
    <dependency>
    	<groupId>org.apache.kafka</groupId>
    	<artifactId>kafka_2.11</artifactId>
    	<version>${kafka.client.version}</version>
    	<exclusions>
    		<exclusion>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-log4j12</artifactId>
    		</exclusion>
    	</exclusions>
    </dependency>
    

    sl4j依赖,自行选择;此处整合springboot,未单独引入

    2.logback的配置

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
    	<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->
    	<property name="LOG_HOME" value="logs" />
    	<property name="SYS_NAME" value="system" />
    	<property name="DATA_NAME" value="data" />
    	<property name="APP_LOGS_FILENAME" value="app" />
    	<property name="EVENT_LOGS_FILENAME" value="event_loss_data" />
       <!--  <springProperty scope="context" name="APP_LOGS_FILENAME" source="logback.filename.applogs"/>
        <springProperty scope="context" name="EVENT_LOGS_FILENAME" source="logback.filename.eventlogs"/> -->
    
    	<appender name="CONSOLE"
    		class="ch.qos.logback.core.ConsoleAppender">
    		<layout class="ch.qos.logback.classic.PatternLayout">
    			<pattern>[%d] [%-5level] [%thread] [%logger] - %msg%n</pattern>
    		</layout>
    	</appender>
    	
    	<appender name="FILE"
    		class="ch.qos.logback.core.rolling.RollingFileAppender">
    		<rollingPolicy
    			class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    			<!--日志文件输出的文件名 -->
    			<FileNamePattern>${LOG_HOME}/${SYS_NAME}/${APP_LOGS_FILENAME}.%d{yyyy-MM-dd}.log
    			</FileNamePattern>
    			<!--日志文件保留天数 -->
    			<MaxHistory>10</MaxHistory>
    		</rollingPolicy>
    
    		<layout class="ch.qos.logback.classic.PatternLayout">
    			<pattern>[%d] [%-5level] [%thread] [%logger] - %msg%n</pattern>
    		</layout>
    		<!--日志文件最大的大小 -->
    		<triggeringPolicy
    			class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
    			<MaxFileSize>100MB</MaxFileSize>
    		</triggeringPolicy>
    	</appender>
    
    
    	<!-- 业务日志:写入kafka -->
    	<appender name="KAFKA-EVENTS"
    		class="com.demo.kafka.logs.KafkaAppender">
    		<layout class="ch.qos.logback.classic.PatternLayout">
    			<pattern>%msg</pattern>
    		</layout>
    	</appender>
    
    	<appender name="ASYNC-KAFKA-EVENTS"
    		class="ch.qos.logback.classic.AsyncAppender">
    		<discardingThreshold>0</discardingThreshold>
    		<queueSize>2048</queueSize>
    		<appender-ref ref="KAFKA-EVENTS" />
    	</appender>
    
    	<logger name="kafka-event" additivity="false">
    		<appender-ref ref="ASYNC-KAFKA-EVENTS" />
    	</logger>
    
    	<!-- 业务日志:异常 写入本地 -->
    	<appender name="LOCAL"
    		class="ch.qos.logback.core.rolling.RollingFileAppender">
    		<rollingPolicy
    			class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><!-- 基于时间的策略 -->
    			<fileNamePattern>${LOG_HOME}/${DATA_NAME}/${EVENT_LOGS_FILENAME}.%d{yyyy-MM-dd}.log
    			</fileNamePattern>
    			<!-- 日志文件保留天数 -->
    			<MaxHistory>10</MaxHistory>
    		</rollingPolicy>
    		<triggeringPolicy
    			class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
    			<!-- 文件大小触发重写新文件 -->
    			<MaxFileSize>100MB</MaxFileSize>
    			<!-- <totalSizeCap>10GB</totalSizeCap> -->
    		</triggeringPolicy>
    		<encoder>
    			<charset>UTF-8</charset>
    			<pattern>[%d] [%-5level] [%thread] [%logger] - %msg%n</pattern>
    		</encoder>
    	</appender>
    	<appender name="ASYNC-LOCAL"
    		class="ch.qos.logback.classic.AsyncAppender">
    		<discardingThreshold>0</discardingThreshold>
    		<queueSize>2048</queueSize>
    		<appender-ref ref="LOCAL" />
    	</appender>
    
    	<!--万一kafka队列不通,记录到本地 -->
    	<logger name="local" additivity="false">
    		<appender-ref ref="ASYNC-LOCAL" />
    	</logger>
    
    	<root level="INFO">
    		<appender-ref ref="CONSOLE" />
    		<appender-ref ref="FILE" />
    	</root>
    	<logger name="org.apache.kafka" level="DEBUG">
    	</logger>
    	<logger name="org.apache.zookeeper" level="DEBUG">
    	</logger>
    
    </configuration>
    

    3.自定义KafkaAppender

    上述logback.xml中的com.demo.kafka.logs.KafkaAppender

    package com.demo.kafka.logs;
    
    import org.apache.kafka.clients.producer.Callback;
    import org.apache.kafka.clients.producer.Producer;
    import org.apache.kafka.clients.producer.ProducerRecord;
    import org.apache.kafka.clients.producer.RecordMetadata;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.Assert;
    
    import com.demo.kafka.KafkaConfigUtils;
    
    import ch.qos.logback.core.AppenderBase;
    import ch.qos.logback.core.Layout;
    
    public class KafkaAppender<E> extends AppenderBase<E> {
    	//此处,logback.xml中的logger的name属性,输出到本地
    	private static final Logger log = LoggerFactory.getLogger("local");
    	protected Layout<E> layout;
    	private Producer<String, String> producer;//kafka生产者
    
    	@Override
    	public void start() {
    		Assert.notNull(layout, "you don't set the layout of KafkaAppender");
    		super.start();
    		this.producer = KafkaConfigUtils.createProducer();
    	}
    
    	@Override
    	public void stop() {
    		super.stop();
    		producer.close();
    		System.out.println("[Stopping KafkaAppender !!!]");
    	}
    
    	@Override
    	protected void append(E event) {
    		String msg = layout.doLayout(event);
    		//拼接消息内容
    		ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>(
    				KafkaConfigUtils.DEFAULT_TOPIC_NAME, msg);
    		System.out.println("[推送数据]:" + producerRecord);
    		//发送kafka的消息
    		producer.send(producerRecord, new Callback() {
    			@Override
    			public void onCompletion(RecordMetadata metadata, Exception exception) {
    				//监听发送结果
    				if (exception != null) {
    					exception.printStackTrace();
    					log.info(msg);
    				} else {
    					System.out.println("[推送数据到kafka成功]:" + metadata);
    				}
    			}
    		});
    	}
    	public Layout<E> getLayout() {
    		return layout;
    	}
    	public void setLayout(Layout<E> layout) {
    		this.layout = layout;
    	}
    
    }
    
    

    4.测试代码段

    //logback.xml中logger的name属性(输出到kafka)
    private static final Logger log = LoggerFactory.getLogger("kafka-event");
    	@Override
    	public void produce(String msgContent) {
    		if (StringUtils.isEmpty(msgContent)) {
    			return;
    		}
    		//打印日志
    		log.info(msgContent);
    	}
    
    

    公众号文章链接:

    https://mp.weixin.qq.com/s/NjHrSYIWWTqNRYx3hKH1Zg

    源码地址

    github:springboot-kafka-logs源码地址

    公众号搜索:DeanKano
    企鹅群号: 561932405

    在这里插入图片描述
    在这里插入图片描述

    展开全文
  • 请移步链接:https://www.javaclub.club/blog/article.html?id=22
    请移步链接:https://aiximiao.com/article?id=68
    
    展开全文
  • Spring+SpringMVC+Mybatis框架整合例子(SSM) 下载

    万次下载 热门讨论 2014-07-21 12:06:07
    本资源对应博文:http://blog.csdn.net/zhshulin/article/details/37956105,可以通过博文进行学习,不建议下载完整源码,博文有详细教程,以及代码。
  • 网上很多整合SSM博客文章并不能让初探ssm的同学思路完全的清晰,可以试着关掉整合教程,摇两下头骨,哈一大口气,就在万事具备的时候,开整,这个时候你可能思路全无 ~中招了咩~ ,还有一些同学依旧在使用eclipse...

空空如也

1 2 3 4 5 ... 20
收藏数 304,605
精华内容 121,842
关键字:

整合