27°

崛起于Springboot2.X + Mybatis-plus(62)

《SpringBoot2.X心法总纲》

项目Git地址:https://gitee.com/mdxl/blog.git

1、项目结构

2、pom依赖

      勾选web、jdbc、mysql、lombok依赖,然后添加其他依赖

<!--mybatis-plus配置依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.2.0</version>
</dependency>
<!--mybatis-plus 代码生成器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.2.0</version>
</dependency>
<!--辅助 mybatis-plus 代码生成器前端模版引擎插件-->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.29</version>
</dependency>

3、配置类

@EnableTransactionManagement
@Configuration
@MapperScan("com.mybatis.plus.service.*.mapper*")
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}

4、启动类

添加注解,扫描mapper.java

@MapperScan("com.mybatis.plus.mapper")

5、Mapper

public interface UserMapper extends BaseMapper<UserEntity> {
@Select({
        "select name from osc_user where id = 2 "
})
String kuozhan();

String kuozhan2();

}

6、Service

public interface UserService extends IService<UserEntity> {
String kuozhan();

String kuozhan2();

IPage&lt;UserEntity&gt; pageList(Page&lt;UserEntity&gt; page, LambdaQueryWrapper&lt;UserEntity&gt; queryWrapper);

}

7、ServiceImpl

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mybatis.plus.entity.UserEntity;
import com.mybatis.plus.mapper.UserMapper;
import com.mybatis.plus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Autowired
UserMapper userMapper;

/**
 * 自己额外扩展的service,用注解方式测试
 */
@Override
public String kuozhan() {
    return userMapper.kuozhan();
}

@Override
public String kuozhan2() {
    return userMapper.kuozhan2();
}

@Override
public IPage&lt;UserEntity&gt; pageList(Page&lt;UserEntity&gt; page, LambdaQueryWrapper&lt;UserEntity&gt; queryWrapper) {
    return userMapper.selectPage(page,queryWrapper);
}

}

8、Controller

User1Controller使用的是Mybatis-plus自带提供方法

@RestController
@RequestMapping(value = "/useMapper")
@Slf4j
public class User1Controller {
@Autowired
UserMapper userMapper;
@GetMapping(value = "/insertUser")
public void insertUser(){
    userMapper.insert(new UserEntity("赵匡胤",21,"北京","篮球"));
}

}

User2Controller使用的是自定义方法

@RequestMapping(value = "/userService")
@RestController
@Slf4j
public class User2Controller {
@Autowired
UserService userService;

@GetMapping(value = "/save")
public void save(){
    userService.save(new UserEntity("烙铁",22,"河北","乒乓球"));
}

@GetMapping(value = "/getOne")
public void getOne(){
    // 使用lambda方式查询,当查询结果为多个报异常,false为查询其中的第一个
    UserEntity userEntity1 = userService.getOne(Wrappers.&lt;UserEntity&gt;lambdaQuery().eq(UserEntity::getAge,21),false);

    // 使用正常方式查询
    QueryWrapper&lt;UserEntity&gt; wrapper = Wrappers.query();
    wrapper.eq("age",21);
    UserEntity userEntity2 = userService.getOne(wrapper,false);

    log.info(userEntity1.toString());
    log.info(userEntity2.toString());
}

/**
 * 自定义扩展service
 */
@GetMapping(value = "/getName")
public void getName(){
    // 注解方式:自定义扩展service
    log.info(userService.kuozhan());
    // xml方式: 自定义扩展service
    log.info(userService.kuozhan2());
}

/**
 * 分页测试
 */
@GetMapping(value = "/page")
public void page(){
    Page&lt;UserEntity&gt; page = new Page&lt;&gt;(2,2);
    IPage&lt;UserEntity&gt; re = userService.pageList(page,Wrappers.&lt;UserEntity&gt;lambdaQuery());
    re.getRecords().stream().forEach(userEntity -&gt; System.out.println(userEntity.getName()));
}

}

9、实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "osc_user")
@ToString
public class UserEntity {
    // 主键,自增长
    @TableId(value = "id",type = IdType.AUTO)
    private int id;
    // 姓名
    private String name;
    // 年龄
    private int age;
    // 地址
    private String address;
    // 爱好
    private String hobby;
public UserEntity(String name, int age, String address, String hobby) {
    this.name = name;
    this.age = age;
    this.address = address;
    this.hobby = hobby;
}

}

10、代码生成接口

@RestController
public class CodeGenerator {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;

/**
 * @param tableName 输入表名,生成对应controller、service、mapper以及xml
 */
@GetMapping(value = "/codeGenerator")
public void codeGenerator(String tableName){
    // 代码生成器
    AutoGenerator mpg = new AutoGenerator();
    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("mujiutian");
    gc.setOpen(false);
    mpg.setGlobalConfig(gc);
    // 数据源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl(url);
    dsc.setDriverName(driverClassName);
    dsc.setUsername(username);
    dsc.setPassword(password);
    mpg.setDataSource(dsc);

    // 包配置
    PackageConfig pc = new PackageConfig();
    pc.setParent("com.mybatis.plus");
    mpg.setPackageInfo(pc);

    // 自定义配置
    InjectionConfig cfg = new InjectionConfig() {
        @Override
        public void initMap() {}
    };

    // 使用模板引擎 freemarker
    String templatePath = "/templates/mapper.xml.ftl";
    // 自定义输出配置
    List&lt;FileOutConfig&gt; focList = new ArrayList&lt;&gt;();
    // 自定义配置会被优先输出
    focList.add(new FileOutConfig(templatePath) {
        @Override
        public String outputFile(TableInfo tableInfo) {
            // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
            return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
        }
    });
    cfg.setFileOutConfigList(focList);
    mpg.setCfg(cfg);

    // 配置模板
    TemplateConfig templateConfig = new TemplateConfig();
    templateConfig.setXml(null);
    mpg.setTemplate(templateConfig);
    // 策略配置
    StrategyConfig strategy = new StrategyConfig();
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    strategy.setEntityLombokModel(true);
    strategy.setRestControllerStyle(false);
    strategy.setInclude(tableName);
    strategy.setControllerMappingHyphenStyle(false);
    mpg.setStrategy(strategy);
    mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    mpg.execute();
}

}

11、UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.plus.mapper.UserMapper">
    <select id="kuozhan2" resultType="java.lang.String">
        select name from osc_user where id = 2
    </select>

</mapper>

12、application.properties

# 端口
server.port=8085
# mysql 连接
spring.datasource.url=jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#mybatis-plus
mybatis-plus.mapper-locations=classpath*:/mapper/*.xml
mybatis-plus.type-aliases-package=com.mybatis.plus.entity
mybatis-plus.configuration.map-underscore-to-camel-case= true

13、测试

分别都成功,然后代码生成器可能延迟几秒,但是也能成功!

 

本文由【木九天】发布于开源中国,原文链接:https://my.oschina.net/mdxlcj/blog/3136357

全部评论: 0

    我有话说: