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
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章