SpringBoot+Mybatis-Plus

SpringBoot+Mybatis-Plus

Mybatis-Plus是在Mybatis的基础上开发的一款持久层框架。之前使用Springboot+Mybatis整合新建项目,如果我们使用逆向工程,我们可以在数据库中先建好数据库和相关表,通过Mybatis逆向工程,可以在项目中自动生成实体类、Mapper接口、以及Mapper.xml文件。
然后我们在application.properties配置文件中配置数据源、mapper.xml的配置信息。

先来回顾一下之前的配置

# thymeleaf

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.mode=HTML5
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false

# datasource
spring.datasource.url=jdbc:mysql://localhost:3306/db_blog?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=1111
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# mybatis
mybatis.mapper-locations=classpath:mapper/*.xml

需要在Mapper接口类上注解@Mapper、ServiceImpl实现类中注解@Service
Mapper接口类上注解@Mapper这个注解配置也可以换成在启动类上通过注解扫描包如下

@SpringBootApplication
@MapperScan(value = "com.jiuyue.mapper")
public class MybatisPlusApplication {

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

}

看起来其实很简单方便,现在我们使用Mybatis-Plus新建项目,也就是Mybatis的升级版了。

从以前的开发新建项目过程中,我们虽然使用了Mybatis的逆向工程来自动生成了部分代码,但是业务层Service接口、ServiceImpl实现类、以及Controller控制器还需要我们手动新建。那么使用Mybatis-Plus我们就可以一步到位。所有的Mybatis-Plus帮你完成。你需要配置一些相关信息,在Controller控制器中注入具体的Service就可以对数据库的数据进行操作了。

项目依赖:

   <dependencies>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.6</version>
        </dependency>
        <!--freemark模板引擎-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

使用代码生成器自动生成代码

/**
 * Create bySeptember
 * 2019/3/13
 * 19:49
 */
public class MpGenerator {
    public static void main(String[] args) {
        GlobalConfig config = new GlobalConfig();
        String dbUrl = "jdbc:mysql://localhost:3306/db_boot?useSSL=false&serverTimezone=UTC";
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername("root")
                .setPassword("1111")
                .setDriverName("com.mysql.cj.jdbc.Driver");
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig
                .setCapitalMode(true)
                //这里结合了Lombok,所以设置为true,如果没有集成Lombok,可以设置为false
                .setEntityLombokModel(true)
                .setNaming(NamingStrategy.underline_to_camel);
        //这里因为我是多模块项目,所以需要加上子模块的名称,以便直接生成到该目录下,如果是单模块项目,可以将后面的去掉
        String projectPath = System.getProperty("user.dir");
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return projectPath + "/src/main/resources/mapper/" + "user"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);

        //设置作者,输出路径,是否重写等属性
        config.setActiveRecord(false)
                .setEnableCache(false)
                .setAuthor("jiuyue")
                .setOutputDir(projectPath + "/src/main/java")
                .setFileOverride(true)
                .setServiceName("%sService");
        new AutoGenerator()
                .setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setTemplateEngine(new FreemarkerTemplateEngine())
                .setCfg(cfg)
                //这里进行包名的设置
                .setPackageInfo(
                        new PackageConfig()
                                .setParent("com.jiuyue.mybatisplus")
                                .setController("controller")
                                .setEntity("entity")
                                .setMapper("mapper")
                                .setServiceImpl("service.impl")
                                .setService("service")
                ).execute();
    }
}

数据库中的表结构

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

运行MpGenerator 类的main方法,就可以看到生成的包。将mapper包下面xml包删掉,因为我们已经在resources中生成了*mapper.xml文件。
这里需要注意,需要在SpringBoot的启动类上配置MapperScan来帮助我们去找到持久层接口的位置。

@SpringBootApplication
@MapperScan(value = "com.jiuyue.mybatisplus.mapper")
public class MybatisPlusApplication {

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

}

在applicaton,properties配置文件配置

server:
  port: 8088

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 1111
    url: jdbc:mysql://localhost:3306/db_boot?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #这个配置会将执行的sql打印出来
  mapper-locations: classpath:mapper/*/*.xml

在代码生成的控制器编写查询列表测试一下:

@Controller
@RequestMapping("/user")
public class UserController {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @ResponseBody
    @RequestMapping("/findAll")
    public List<User> findAll(){
        logger.info("information====");
        return userService.list();
    }
}

浏览器输出

[{"id":1,"userName":"jiuyue","password":"jiuyue"},{"id":2,"userName":"September","password":"aa"}]

为什么我们只需要在controller层中直接去调用就可以获得到列表,这是因为Mybatis-Plus给我们封装了一系列的CRUD的基础接口,在通过代码生成器生成的UserService接口实际上是继承了IService接口的,而UserServiceImpl则是继承ServiceImpl,所以就继承到一些基础的实现。

public interface UserService extends IService<User> {

}

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}

IService则给我们提供了以下方法来实现基础的CRUD:

/**
 * <p>
 * 顶级 Service
 * </p>
 *
 * @author hubin
 * @since 2018-06-23
 */
public interface IService<T> {

    boolean save(T entity);

    default boolean saveBatch(Collection<T> entityList) {
        return saveBatch(entityList, 1000);
    }

    boolean saveBatch(Collection<T> entityList, int batchSize);

    default boolean saveOrUpdateBatch(Collection<T> entityList) {
        return saveOrUpdateBatch(entityList, 1000);
    }

    boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

    boolean removeById(Serializable id);

    boolean removeByMap(Map<String, Object> columnMap);

    boolean remove(Wrapper<T> queryWrapper);

    boolean removeByIds(Collection<? extends Serializable> idList);

    boolean updateById(T entity);
    //...

同样的,BaseMapper接口也提供了一些实现:

public interface UserMapper extends BaseMapper<User> {

}

/**
 * @author hubin
 * @since 2016-01-23
 */
public interface BaseMapper<T> {

    int insert(T entity);

    int deleteById(Serializable id);

    int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);


    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    int updateById(@Param(Constants.ENTITY) T entity);
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

    T selectById(Serializable id);

    List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
    T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}

通过这些基础的实现,我们可以完成基本的对数据库的操作,而省去了编写Service和ServiceImpl的时间,从编码效率上来讲比起JPA更胜一筹。

条件构造器

条件构造器可以构造一些查询条件来获取我们指定的数据,同时可以结合Lambda表达式来使用,下面我们直接来编写两个例子:

    @ResponseBody
    @RequestMapping("/findUserByUserName")
    public User findUserByUserName(@RequestParam("userName") String userName){
        logger.info("information====");
        return userService.findUserByUserName(userName);
    }

实现类

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User findUserByUserName(String userName) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUserName,userName);
        return userMapper.selectOne(wrapper);
    }
}

使用Lambda表达式就足够直观的可以看出我们是想查询出userName = ?的数据

http://localhost:8088/user/findUserByUserName?userName=jiuyue
{"id":1,"userName":"jiuyue","password":"jiuyue"}

条件构造器的用法还有很多,这里不在一一罗列,有需要可以去官网查看文档。

分页查询

如果我们需要分页查询数据,可以使用Mybatis-Plus自带的分页插件。

    @ResponseBody
    @RequestMapping("/findAllByPage")
    public IPage<User> findAllByPage(){
        Page<User> userPage = new Page<>(1,5);
        logger.info("information====");
        return userService.page(userPage);
    }

我们只需要构建一个Page对象,并初始化我们所需的页数(page)和每页数据(pageSize),然后将其作为page()方法的参数传入即可。下面是分页查询结果:

{
    "records":[
        {
            "id":1,
            "userName":"jiuyue",
            "password":"jiuyue"
        },
        {
            "id":2,
            "userName":"September",
            "password":"aa"
        },
        {
            "id":3,
            "userName":"September",
            "password":"September"
        },
        {
            "id":4,
            "userName":"September",
            "password":"September"
        },
        {
            "id":5,
            "userName":"September",
            "password":"September"
        },
        {
            "id":6,
            "userName":"fenye",
            "password":"fenye"
        }
    ],
    "total":0,
    "size":5,
    "current":1,
    "searchCount":true,
    "pages":0
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值