8.mybatis与SpringBoot集成

本来想写一篇关于ssm集成方面的文章,但是考虑到现在基本上使用的是SpringBoot框架进行开发,因此直接写SpringBoot框架集成mybatis更好。

一、创建maven项目并导入相应的包


    4.0.0
    com.qiu
    mybatis
    0.0.1-SNAPSHOT
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.0.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
    
        
            org.springframework.boot
            spring-boot-devtools
            runtime
        
        
        
            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.26
        
        
        
            com.github.pagehelper
            pagehelper
            4.1.6
        
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.0
        
        
        
            org.mybatis.generator
            mybatis-generator-core
            1.3.5
        

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            

        
    

二、mysql中创建数据表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `user_password` varchar(255) DEFAULT NULL,
  `user_email` varchar(255) DEFAULT NULL,
  `user_info` varchar(255) DEFAULT NULL,
  `head_img` varchar(255) DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

三、使用代码生成器自动生成相关的entity、xxxMapper和xxxMapper映射文件。

参照之前的mybatis代码生成器使用博客:https://www.jianshu.com/p/b6a0ac3ba17c

  • 在生成的xxxMapper接口上加上@Mapper注解,否则Springboot扫描不到该接口,会报错误。然后自定义一个方法
@Mapper
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);
    //自定义一个方法
    ListfindAllUser();
}
  • 生成的model类
public class User {
    private Integer id;
    private String userName;
    private String userPassword;
    private String userEmail;
    private String userInfo;
    private String headImg;
    private Date createTime;
    ...省略getter/setter
  • 把UserMapper.xml文件放在src/main/resource/mapper目录下面,然后在UserMapper.xml文件中添加自定义方法



  
    
    
    
    
    
    
    
  
  
    id, user_name, user_password, user_email, user_info, head_img, create_time
  
   
  
  
  
    delete from user
    where id = #{id,jdbcType=INTEGER}
  
  
    insert into user (id, user_name, user_password, 
      user_email, user_info, head_img, 
      create_time)
    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR}, 
      #{userEmail,jdbcType=VARCHAR}, #{userInfo,jdbcType=VARCHAR}, #{headImg,jdbcType=VARCHAR}, 
      #{createTime,jdbcType=TIMESTAMP})
  
  
    insert into user
    
      
        id,
      
      
        user_name,
      
      
        user_password,
      
      
        user_email,
      
      
        user_info,
      
      
        head_img,
      
      
        create_time,
      
    
    
      
        #{id,jdbcType=INTEGER},
      
      
        #{userName,jdbcType=VARCHAR},
      
      
        #{userPassword,jdbcType=VARCHAR},
      
      
        #{userEmail,jdbcType=VARCHAR},
      
      
        #{userInfo,jdbcType=VARCHAR},
      
      
        #{headImg,jdbcType=VARCHAR},
      
      
        #{createTime,jdbcType=TIMESTAMP},
      
    
  
  
    update user
    
      
        user_name = #{userName,jdbcType=VARCHAR},
      
      
        user_password = #{userPassword,jdbcType=VARCHAR},
      
      
        user_email = #{userEmail,jdbcType=VARCHAR},
      
      
        user_info = #{userInfo,jdbcType=VARCHAR},
      
      
        head_img = #{headImg,jdbcType=VARCHAR},
      
      
        create_time = #{createTime,jdbcType=TIMESTAMP},
      
    
    where id = #{id,jdbcType=INTEGER}
  
  
    update user
    set user_name = #{userName,jdbcType=VARCHAR},
      user_password = #{userPassword,jdbcType=VARCHAR},
      user_email = #{userEmail,jdbcType=VARCHAR},
      user_info = #{userInfo,jdbcType=VARCHAR},
      head_img = #{headImg,jdbcType=VARCHAR},
      create_time = #{createTime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=INTEGER}
  

四、创建一个配置类,并配置好分页插件

@Configuration
public class MybatisConfig {
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper=new PageHelper();
        Properties properties=new Properties();
//该参数默认为false ,设置为true时,会将RowBounds第一个参数offset当
//成pageNum页码使用,和startPage中的pageNum效果一样
        properties.setProperty("offsetAsPageNum","true");
//该参数默认为false,设置为true时,使用RowBounds分页会进行count查询 
        properties.setProperty("rowBoundsWithCount","true");
//分页参数合理化,默认false禁用
        properties.setProperty("reasonable","true");
//配置mysql数据库方言
        properties.setProperty("dialect","mysql");
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}

五、创建UserService和UserServiceImp

  • UserService接口
public interface UserService {
    int addUser(User user);
    List findAllUser(int pageNum, int pageSize);
}
  • UserServiceImp实现类
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public int addUser(User user) {
        return userMapper.insert(user);
    }
    @Override
    public List findAllUser(int pageNum, int pageSize) {
        //进行分页,必须在mybatis从数据库获取数据之前
        PageHelper.startPage(pageNum, pageSize);
        List findAllUser = userMapper.findAllUser();
        return findAllUser;
    }
}

六、创建controller,执行web相关操作

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/addUser")
    public String addUser() {
        User user=new User();
        user.setCreateTime(new Date());
        user.setUserEmail("[email protected]");
        user.setUserInfo("hahah");
        user.setUserName("qiu");
        user.setUserPassword("1233");
        int addUser = userService.addUser(user);
        return addUser!=0?"插入成功":"插入失败";
    }
    @RequestMapping("/getUserByPage")
//默认pageNum为1,pageSize为1
    public String getUsersByPage(@RequestParam(value="pageNum",defaultValue="1")Integer pageNum,
     @RequestParam(value="pageSize",defaultValue="2")Integer pageSize) {
         List list = userService.findAllUser(pageNum, pageSize);
         list.forEach(System.out::println);
         return list.toString();
    }

七、创建springboot启动类

@SpringBootApplication
public class SpringbootMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}

八、在classpath目录下面创建SpringBoot配置文件application.properties

#tomcat端口
server.port=8082
#datasource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# 数据库访问配置
# 主数据源,默认的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.s
tat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
spring.datasource.useGlobalDataSourceStat=true

#mybatis相关
#别名
mybatis.type-aliases-package=com.qiu.model
#映射配置文件位置
mybatis.mapper-locations=classpath:mapper/*.xml

九、启动SpringBoot项目并进行访问

  • 先进行数据插入:http://localhost:8082/addUser
  • 然后进行分页查询:http://localhost:8082/getUserByPage?pageNum=3&pageSize=1

你可能感兴趣的:(8.mybatis与SpringBoot集成)