SpringBoot集成MybatisPlus

1、Mybatis和MybatisPlus区别

  Mybatis:ssm框架中,除了要写xml配置,还要写xml的sql文件,比如:usermapper.xml

  MybatisPlus:基本上不用写一条SQL,如果业务层不复杂,完全不用业务层

  MybatisPlus特性:无侵入,依赖少,防止SQL注入,通用CRUD,主键生成策略,代码生成,内置分页插件

    主键生成策略:IdType.AUTO(自动)、IdType.INPUT(用户输入)、IdType.ID_WORKER(自动)、IdType.UUID(自动)

    配置方法:主键ID上加注解,@TableId(value="ID",type="IdType.AUTO"),一般情况下推荐大家使用自动增长主键

2、配置文件(application.properties)  

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root

spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false

3、pom.xml中引入mybatis-plus的jar包

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>2.3.3</version>
</dependency>

4、创建MybatisPlusConfig类

package com.cppdy.config;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;

@Configuration
public class MybatisPlusConfig {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private MybatisProperties properties;
    @Autowired
    private ResourceLoader resourceLoader = new DefaultResourceLoader();
    @Autowired(required = false)
    private Interceptor[] interceptors;
    @Autowired(required = false)
    private DatabaseIdProvider databaseldProvider;

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }

    /**
     * 这里全部使用mybatis-autoconfigure已经自动加载的资源。不手动指定配置文件和mybatis-boot的配置文件同步
     */

    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
        MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
        mybatisPlus.setDataSource(dataSource);
        mybatisPlus.setVfs(SpringBootVFS.class);
        if (StringUtils.hasText(this.properties.getConfigLocation())) {
            mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
        }
        mybatisPlus.setConfiguration(properties.getConfiguration());
        if (!ObjectUtils.isEmpty(this.interceptors)) {
            mybatisPlus.setPlugins(this.interceptors);
        }
        MybatisConfiguration mc = new MybatisConfiguration();
        mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        mybatisPlus.setConfiguration(mc);
        if (this.databaseldProvider != null) {
            mybatisPlus.setDatabaseIdProvider(this.databaseldProvider);
        }
        if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
            mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        }
        if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
            mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
        }
        if (ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
            mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
        }
        return mybatisPlus;
    }
}

5、UserMapper接口

package com.cppdy.mapper;

import org.apache.ibatis.annotations.Mapper;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.cppdy.entity.User;

@Mapper
public interface UserMapper extends BaseMapper<User>{

}

6、UserService接口

package com.cppdy.service;

public interface UserService {

    public void update(String username, int id);

}

7、UserServiceImpl实现类

package com.cppdy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cppdy.entity.User;
import com.cppdy.mapper.UserMapper;
import com.cppdy.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    // 开启事务管理
    @Transactional
    public void update(String username, int id) {

        User user = userMapper.selectById(id);
        user.setUsername(username);
        // 更新一条数据
        userMapper.updateById(user);

    }

}

8、HelloWordController类

package com.cppdy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cppdy.entity.User;
import com.cppdy.mapper.UserMapper;
import com.cppdy.service.UserService;

@RestController
public class HelloWordController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @RequestMapping("hello")
    public String hello() {

        return "HelloWord";
    }

    @RequestMapping("excep")
    public String excep() {

        int a = 2 / 0;

        return "Hello Exception";
    }

    @RequestMapping("getUserById")
    public Object getUserById(int id) {
        
        return userMapper.selectById(id);
    }

    @RequestMapping("insert")
    public void insert(String username) {
        User user = new User();
        user.setUsername(username);
        userMapper.insert(user);
    }

    @RequestMapping("update")
    public void update(String username, int id) {

        userService.update(username, id);
    }

}

 

posted @ 2018-12-01 15:31  知识追求者  阅读(739)  评论(0编辑  收藏  举报