spring boot mybatis 整合教程
本项目使用的环境:
- 开发工具:intellij idea 2017.1.3
- springboot: 1.5.6
- :1.8.0_161
- maven:3.3.9
额外功能
- pagehelper 分页插件
- mybatis generator 自动生成代码插件
步骤:
1. 创建一个springboot项目:
2. 创建项目的文件结构以及jdk的版本
3. 选择项目所需要的依赖
然后点击finish
4. 看一下文件的结构:
5. 查看一下pom.xml:
1 <?xml version="1.0" encoding="utf-8"?> 2 <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 3 xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelversion>4.0.0</modelversion> 5 6 <groupid>com.winter</groupid> 7 <artifactid>springboot-mybatis-demo</artifactid> 8 <version>0.0.1-snapshot</version> 9 <packaging>jar</packaging> 10 11 <name>springboot-mybatis-demo</name> 12 <description>demo project for spring boot</description> 13 14 <parent> 15 <groupid>org.springframework.boot</groupid> 16 <artifactid>spring-boot-starter-parent</artifactid> 17 <version>1.5.6.release</version> 18 <relativepath/> <!-- lookup parent from repository --> 19 </parent> 20 21 <properties> 22 <project.build.sourceencoding>utf-8</project.build.sourceencoding> 23 <project.reporting.outputencoding>utf-8</project.reporting.outputencoding> 24 <java.version>1.7</java.version> 25 </properties> 26 27 <dependencies> 28 <dependency> 29 <groupid>org.mybatis.spring.boot</groupid> 30 <artifactid>mybatis-spring-boot-starter</artifactid> 31 <version>1.3.0</version> 32 </dependency> 33 <dependency> 34 <groupid>org.springframework.boot</groupid> 35 <artifactid>spring-boot-starter-thymeleaf</artifactid> 36 </dependency> 37 <dependency> 38 <groupid>org.springframework.boot</groupid> 39 <artifactid>spring-boot-starter-web</artifactid> 40 </dependency> 41 42 <dependency> 43 <groupid>org.springframework.boot</groupid> 44 <artifactid>spring-boot-starter-test</artifactid> 45 <scope>test</scope> 46 </dependency> 47 <dependency> 48 <groupid>mysql</groupid> 49 <artifactid>mysql-connector-java</artifactid> 50 <version>5.1.35</version> 51 </dependency> 52 53 54 <dependency> 55 <groupid>com.fasterxml.jackson.core</groupid> 56 <artifactid>jackson-core</artifactid> 57 </dependency> 58 <dependency> 59 <groupid>com.fasterxml.jackson.core</groupid> 60 <artifactid>jackson-databind</artifactid> 61 </dependency> 62 <dependency> 63 <groupid>com.fasterxml.jackson.datatype</groupid> 64 <artifactid>jackson-datatype-joda</artifactid> 65 </dependency> 66 <dependency> 67 <groupid>com.fasterxml.jackson.module</groupid> 68 <artifactid>jackson-module-parameter-names</artifactid> 69 </dependency> 70 <!-- 分页插件 --> 71 <dependency> 72 <groupid>com.github.pagehelper</groupid> 73 <artifactid>pagehelper-spring-boot-starter</artifactid> 74 <version>1.1.2</version> 75 </dependency> 76 <!-- alibaba的druid数据库连接池 --> 77 <dependency> 78 <groupid>com.alibaba</groupid> 79 <artifactid>druid-spring-boot-starter</artifactid> 80 <version>1.1.0</version> 81 </dependency> 82 </dependencies> 83 84 <build> 85 <plugins> 86 <plugin> 87 <groupid>org.springframework.boot</groupid> 88 <artifactid>spring-boot-maven-plugin</artifactid> 89 </plugin> 90 <!-- mybatis generator 自动生成代码插件 --> 91 <plugin> 92 <groupid>org.mybatis.generator</groupid> 93 <artifactid>mybatis-generator-maven-plugin</artifactid> 94 <version>1.3.2</version> 95 <configuration> 96 <configurationfile>${basedir}/src/main/resources/generator/generatorconfig.xml</configurationfile> 97 <overwrite>true</overwrite> 98 <verbose>true</verbose> 99 </configuration> 100 </plugin> 101 </plugins> 102 </build> 103 104 105 </project>
6. 项目不使用application.properties文件 而使用更加简洁的application.yml文件:
将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,
文件的内容如下:
1 server: 2 port: 8080 3 4 spring: 5 datasource: 6 name: test 7 url: jdbc:mysql://127.0.0.1:3306/depot 8 username: root 9 password: root 10 # 使用druid数据源 11 type: com.alibaba.druid.pool.druiddatasource 12 driver-class-name: com.mysql.jdbc.driver 13 filters: stat 14 maxactive: 20 15 initialsize: 1 16 maxwait: 60000 17 minidle: 1 18 timebetweenevictionrunsmillis: 60000 19 minevictableidletimemillis: 300000 20 validationquery: select 'x' 21 testwhileidle: true 22 testonborrow: false 23 testonreturn: false 24 poolpreparedstatements: true 25 maxopenpreparedstatements: 20 26 27 ## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别 28 mybatis: 29 mapper-locations: classpath:mapping/*.xml #注意:一定要对应mapper映射xml文件的所在路径 30 type-aliases-package: com.winter.model # 注意:对应实体类的路径 31 32 #pagehelper分页插件 33 pagehelper: 34 helperdialect: mysql 35 reasonable: true 36 supportmethodsarguments: true 37 params: count=countsql
7. 创建数据库:
1 create database mytest; 2 3 create table t_user( 4 user_id int not null primary key auto_increment, 5 user_name varchar(255) not null , 6 password varchar(255) not null , 7 phone varchar(255) not null 8 ) engine=innodb auto_increment=1000 default charset=utf8;
8. 使用mybatis generator 自动生成代码:
- 配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/generator/generatorconfig.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <!doctype generatorconfiguration 3 public "-//mybatis.org//dtd mybatis generator configuration 1.0//en" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 <generatorconfiguration> 6 <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包--> 7 <classpathentry location="e:\developer\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/> 8 <context id="db2tables" targetruntime="mybatis3"> 9 <commentgenerator> 10 <property name="suppressdate" value="true"/> 11 <!-- 是否去除自动生成的注释 true:是 : false:否 --> 12 <property name="suppressallcomments" value="true"/> 13 </commentgenerator> 14 <!--数据库链接url,用户名、密码 --> 15 <jdbcconnection driverclass="com.mysql.jdbc.driver" connectionurl="jdbc:mysql://127.0.0.1/mytest" userid="root" password="root"> 16 </jdbcconnection> 17 <javatyperesolver> 18 <property name="forcebigdecimals" value="false"/> 19 </javatyperesolver> 20 <!-- 生成模型的包名和位置--> 21 <javamodelgenerator targetpackage="com.winter.model" targetproject="src/main/java"> 22 <property name="enablesubpackages" value="true"/> 23 <property name="trimstrings" value="true"/> 24 </javamodelgenerator> 25 <!-- 生成映射文件的包名和位置--> 26 <sqlmapgenerator targetpackage="mapping" targetproject="src/main/resources"> 27 <property name="enablesubpackages" value="true"/> 28 </sqlmapgenerator> 29 <!-- 生成dao的包名和位置--> 30 <javaclientgenerator type="xmlmapper" targetpackage="com.winter.mapper" targetproject="src/main/java"> 31 <property name="enablesubpackages" value="true"/> 32 </javaclientgenerator> 33 <!-- 要生成的表 tablename是数据库中的表名或视图名 domainobjectname是实体类名--> 34 <table tablename="t_user" domainobjectname="user" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="false" selectbyexamplequeryid="false"></table> 35 </context> 36 </generatorconfiguration>
- 点击run-edit configurations
- 添加配置
-
运行
注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,切记
最后生成的文件以及结构:
9. 生成的文件
usermapper.java
1 package com.winter.mapper; 2 3 import com.winter.model.user; 4 5 public interface usermapper { 6 int deletebyprimarykey(integer userid); 7 8 int insert(user record); 9 10 int insertselective(user record); 11 12 user selectbyprimarykey(integer userid); 13 14 int updatebyprimarykeyselective(user record); 15 16 int updatebyprimarykey(user record); 17 //这个方式我自己加的 18 list<user> selectalluser(); 19 }
user.java
1 package com.winter.model; 2 3 public class user { 4 private integer userid; 5 6 private string username; 7 8 private string password; 9 10 private string phone; 11 12 public integer getuserid() { 13 return userid; 14 } 15 16 public void setuserid(integer userid) { 17 this.userid = userid; 18 } 19 20 public string getusername() { 21 return username; 22 } 23 24 public void setusername(string username) { 25 this.username = username == null ? null : username.trim(); 26 } 27 28 public string getpassword() { 29 return password; 30 } 31 32 public void setpassword(string password) { 33 this.password = password == null ? null : password.trim(); 34 } 35 36 public string getphone() { 37 return phone; 38 } 39 40 public void setphone(string phone) { 41 this.phone = phone == null ? null : phone.trim(); 42 } 43 }
对于sql语句这种黄色的背景,真心是看不下去了(解决方案):
**usermapper.xml **
1 <?xml version="1.0" encoding="utf-8" ?> 2 <!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.winter.mapper.usermapper" > 4 <resultmap id="baseresultmap" type="com.winter.model.user" > 5 <id column="user_id" property="userid" jdbctype="integer" /> 6 <result column="user_name" property="username" jdbctype="varchar" /> 7 <result column="password" property="password" jdbctype="varchar" /> 8 <result column="phone" property="phone" jdbctype="varchar" /> 9 </resultmap> 10 <sql id="base_column_list" > 11 user_id, user_name, password, phone 12 </sql> 13 <select id="selectbyprimarykey" resultmap="baseresultmap" parametertype="java.lang.integer" > 14 select 15 <include refid="base_column_list" /> 16 from t_user 17 where user_id = #{userid,jdbctype=integer} 18 </select> 19 <!-- 这个方法是我自己加的 --> 20 <select id="selectalluser" resultmap="baseresultmap"> 21 select 22 <include refid="base_column_list" /> 23 from t_user 24 </select> 25 <delete id="deletebyprimarykey" parametertype="java.lang.integer" > 26 delete from t_user 27 where user_id = #{userid,jdbctype=integer} 28 </delete> 29 <insert id="insert" parametertype="com.winter.model.user" > 30 insert into t_user (user_id, user_name, password, 31 phone) 32 values (#{userid,jdbctype=integer}, #{username,jdbctype=varchar}, #{password,jdbctype=varchar}, 33 #{phone,jdbctype=varchar}) 34 </insert> 35 <insert id="insertselective" parametertype="com.winter.model.user" > 36 insert into t_user 37 <trim prefix="(" suffix=")" suffixoverrides="," > 38 <if test="userid != null" > 39 user_id, 40 </if> 41 <if test="username != null" > 42 user_name, 43 </if> 44 <if test="password != null" > 45 password, 46 </if> 47 <if test="phone != null" > 48 phone, 49 </if> 50 </trim> 51 <trim prefix="values (" suffix=")" suffixoverrides="," > 52 <if test="userid != null" > 53 #{userid,jdbctype=integer}, 54 </if> 55 <if test="username != null" > 56 #{username,jdbctype=varchar}, 57 </if> 58 <if test="password != null" > 59 #{password,jdbctype=varchar}, 60 </if> 61 <if test="phone != null" > 62 #{phone,jdbctype=varchar}, 63 </if> 64 </trim> 65 </insert> 66 <update id="updatebyprimarykeyselective" parametertype="com.winter.model.user" > 67 update t_user 68 <set > 69 <if test="username != null" > 70 user_name = #{username,jdbctype=varchar}, 71 </if> 72 <if test="password != null" > 73 password = #{password,jdbctype=varchar}, 74 </if> 75 <if test="phone != null" > 76 phone = #{phone,jdbctype=varchar}, 77 </if> 78 </set> 79 where user_id = #{userid,jdbctype=integer} 80 </update> 81 <update id="updatebyprimarykey" parametertype="com.winter.model.user" > 82 update t_user 83 set user_name = #{username,jdbctype=varchar}, 84 password = #{password,jdbctype=varchar}, 85 phone = #{phone,jdbctype=varchar} 86 where user_id = #{userid,jdbctype=integer} 87 </update> 88 </mapper>
10. 打开类springbootmybatisdemoapplication.java,这个是springboot的启动类。我们需要添加点东西:
1 package com.winter; 2 3 import org.mybatis.spring.annotation.mapperscan; 4 import org.springframework.boot.springapplication; 5 import org.springframework.boot.autoconfigure.springbootapplication; 6 7 @springbootapplication 8 @mapperscan("com.winter.mapper")//将项目中对应的mapper类的路径加进来就可以了 9 public class springbootmybatisdemoapplication { 10 11 public static void main(string[] args) { 12 springapplication.run(springbootmybatisdemoapplication.class, args); 13 } 14 }
注意:@mapperscan("com.winter.mapper")
这个注解非常的关键,这个对应了项目中mapper(dao)所对应的包路径,很多同学就是这里忘了加导致异常的
11. 到这里所有的搭建工作都完成了,接下来就是测试的工作,没使用junit4进行测试:
首先看一下完成之后的文件的结构:
现在controller,service层的代码都写好:
usercontroller.java
1 package com.winter.controller; 2 3 import com.winter.model.user; 4 import com.winter.service.userservice; 5 import org.springframework.beans.factory.annotation.autowired; 6 import org.springframework.stereotype.controller; 7 import org.springframework.web.bind.annotation.pathvariable; 8 import org.springframework.web.bind.annotation.requestmapping; 9 import org.springframework.web.bind.annotation.responsebody; 10 11 /** 12 * created by administrator on 2017/8/16. 13 */ 14 @controller 15 @requestmapping(value = "/user") 16 public class usercontroller { 17 18 @autowired 19 private userservice userservice; 20 21 @responsebody 22 @requestmapping(value = "/add", produces = {"application/json;charset=utf-8"}) 23 public int adduser(user user){ 24 return userservice.adduser(user); 25 } 26 27 @responsebody 28 @requestmapping(value = "/all/{pagenum}/{pagesize}", produces = {"application/json;charset=utf-8"}) 29 public object findalluser(@pathvariable("pagenum") int pagenum, @pathvariable("pagesize") int pagesize){ 30 31 return userservice.findalluser(pagenum,pagesize); 32 } 33 }
userservice.java
1 package com.winter.service; 2 3 import com.winter.model.user; 4 5 import java.util.list; 6 7 /** 8 * created by administrator on 2017/8/16. 9 */ 10 public interface userservice { 11 12 int adduser(user user); 13 14 list<user> findalluser(int pagenum, int pagesize); 15 }
userserviceimpl.java
1 package com.winter.service.impl; 2 3 import com.github.pagehelper.pagehelper; 4 import com.winter.mapper.usermapper; 5 import com.winter.model.user; 6 import com.winter.service.userservice; 7 import org.springframework.beans.factory.annotation.autowired; 8 import org.springframework.stereotype.service; 9 10 import java.util.list; 11 12 /** 13 * created by administrator on 2017/8/16. 14 */ 15 @service(value = "userservice") 16 public class userserviceimpl implements userservice { 17 18 @autowired 19 private usermapper usermapper;//这里会报错,但是并不会影响 20 21 @override 22 public int adduser(user user) { 23 24 return usermapper.insertselective(user); 25 } 26 27 /* 28 * 这个方法中用到了我们开头配置依赖的分页插件pagehelper 29 * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可; 30 * pagenum 开始页数 31 * pagesize 每页显示的数据条数 32 * */ 33 @override 34 public list<user> findalluser(int pagenum, int pagesize) { 35 //将参数传给这个方法就可以实现物理分页了,非常简单。 36 pagehelper.startpage(pagenum, pagesize); 37 return usermapper.selectalluser(); 38 } 39 }
如果强迫症看不下去那个报错:(解决方法)
测试我使用了idea一个很用心的功能。
可以发http请求的插件:
点击左侧的运行按钮就可以发送请求了;
如果返回值正确 说明你已经搭建成功了!!
ps:如果出现mapper注入不了的情况,请检查版本,当前博客的搭建方法只适合1.5.*版本的。
上一篇: 猕猴桃营养丰富,那么吃多了猕猴桃会如何
下一篇: 辣妈赵薇保养得当,37仍嫩如少女
推荐阅读
-
使用maven整合Spring+SpringMVC+Mybatis框架详细步骤(图文)
-
spring+springmvc+mybatis+maven入门实战(超详细教程)
-
Spring MVC+FastJson+hibernate-validator整合的完整实例教程
-
Spring boot项目部署到云服务器小白教程详解
-
Spring Boot整合mybatis(一)实例代码
-
spring Boot与Mybatis整合优化详解
-
详解Spring Boot中MyBatis的使用方法
-
Spring Boot整合RabbitMQ开发实战详解
-
Spring Boot + Kotlin整合MyBatis的方法教程
-
spring集成mybatis原理(spring和mybatis整合步骤)