新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

怎么在Springboot中整合Mybatis

怎么在Spring boot中整合Mybatis ?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

延川ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联建站的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

步骤:

1.创建一个springboot项目:


怎么在Spring boot中整合Mybatis 

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


怎么在Spring boot中整合Mybatis

3.选择项目所需要的依赖


怎么在Spring boot中整合Mybatis
怎么在Spring boot中整合Mybatis 

然后点击finish

5.看一下文件的结构:


怎么在Spring boot中整合Mybatis

6.查看一下pom.xml:



 4.0.0
 com.winter
 springboot-mybatis-demo
 0.0.1-SNAPSHOT
 jar
 springboot-mybatis-demo
 Demo project for Spring Boot
 
 org.springframework.boot
 spring-boot-starter-parent
 1.5.6.RELEASE
  
 
 
 UTF-8
 UTF-8
 1.7
 
 
 
  org.mybatis.spring.boot
  mybatis-spring-boot-starter
  1.3.0
 
 
  org.springframework.boot
  spring-boot-starter-thymeleaf
 
 
  org.springframework.boot
  spring-boot-starter-web
 
 
  org.springframework.boot
  spring-boot-starter-test
  test
 
 
  MySQL
  mysql-connector-java
  5.1.35
 
 
  com.fasterxml.jackson.core
  jackson-core
 
 
  com.fasterxml.jackson.core
  jackson-databind
 
 
  com.fasterxml.jackson.datatype
  jackson-datatype-joda
 
 
  com.fasterxml.jackson.module
  jackson-module-parameter-names
 
 
 
  com.github.pagehelper
  pagehelper-spring-boot-starter
  1.1.2
 
 
 
  com.alibaba
  druid-spring-boot-starter
  1.1.0
 
 
 
 
  
  org.springframework.boot
  spring-boot-maven-plugin
  
  
  
  org.mybatis.generator
  mybatis-generator-maven-plugin
  1.3.2
  
   ${basedir}/src/main/resources/generator/generatorConfig.xml
   true
   true
  
  
 
 

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




 
 
 
 
  
  
  
 
 
 
 
 
  
 
 
 
  
  
 
 
 
  
 
 
 
  
 
 
 
 

点击run-Edit Configurations

怎么在Spring boot中整合Mybatis

添加配置

怎么在Spring boot中整合Mybatis

运行

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


怎么在Spring boot中整合Mybatis

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

怎么在Spring boot中整合Mybatis

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 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语句这种黄色的背景,真心是看不下去了(解决方案):


怎么在Spring boot中整合Mybatis

UserMapper.xml




 
 
 
 
 
 
 
 user_id, user_name, password, phone
 
 
 select 
 
 from t_user
 where user_id = #{userId,jdbcType=INTEGER}
 
 
 
 select
 
 from t_user
 
 
 delete from t_user
 where user_id = #{userId,jdbcType=INTEGER}
 
 
 insert into t_user (user_id, user_name, password, 
 phone)
 values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
 #{phone,jdbcType=VARCHAR})
 
 
 insert into t_user
 
 
 user_id,
 
 
 user_name,
 
 
 password,
 
 
 phone,
 
 
 
 
 #{userId,jdbcType=INTEGER},
 
 
 #{userName,jdbcType=VARCHAR},
 
 
 #{password,jdbcType=VARCHAR},
 
 
 #{phone,jdbcType=VARCHAR},
 
 
 
 
 update t_user
 
 
 user_name = #{userName,jdbcType=VARCHAR},
 
 
 password = #{password,jdbcType=VARCHAR},
 
 
 phone = #{phone,jdbcType=VARCHAR},
 
 
 where user_id = #{userId,jdbcType=INTEGER}
 
 
 update t_user
 set user_name = #{userName,jdbcType=VARCHAR},
 password = #{password,jdbcType=VARCHAR},
 phone = #{phone,jdbcType=VARCHAR}
 where user_id = #{userId,jdbcType=INTEGER}
 

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进行测试:
首先看一下完成之后的文件的结构:


怎么在Spring boot中整合Mybatis

现在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 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 findAllUser(int pageNum, int pageSize) {
 //将参数传给这个方法就可以实现物理分页了,非常简单。
 PageHelper.startPage(pageNum, pageSize);
 return userMapper.selectAllUser();
 }
}

如果强迫症看不下去那个报错:(解决方法)


怎么在Spring boot中整合Mybatis

测试我使用了idea一个很用心的功能。

可以发http请求的插件:


怎么在Spring boot中整合Mybatis

怎么在Spring boot中整合Mybatis

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。


当前名称:怎么在Springboot中整合Mybatis
网页路径:http://www.wjwzjz.com/article/pjdsjp.html
在线咨询
服务热线
服务热线:028-86922220
TOP