初探mybatis-plus

 

添加依赖

   com.baomidou
   mybatis-plus
   2.3

配置扫描文件路径: 

@MapperScan(value = {"com.baomidou.mybatisplus.samples.quickstart.mapper"})
    

配置mapers文件加载路径: 

mybatis-plus.mapper-locations=classpath*:mappers/*.xml

 通过XML文件配置属性:

需要添加加载配置文件注解:@ContextConfiguration(locations = {"classpath*:config.xml"}) 以下是config.xml的内容:
<bean id="dataSourceclass="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" >
    <property name="databaseName" value=""/>
    <property name="url" value=""/>
    <property name="username" value=""/>
    <property name="password" value=""/>
bean>
 
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSourceref="dataSource"/>
    <property name="mapperLocationsvalue="classpath:mappers/*.xml"/>
  以下非必填配置
    <property name="globalConfig" ref="globalConfig"/>
    <property name="plugins">
        <array>
            <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">bean>
        array>
    property>
bean>
<bean id="globalConfigclass="com.baomidou.mybatisplus.core.config.GlobalConfig">
    <property name="dbConfig" ref="dbConfig"/>
bean>
 
<bean id="dbConfigclass="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
    <property name="keyGenerator" ref="keyGenerator"/>
bean>
 
<bean id="keyGeneratorclass="com.baomidou.mybatisplus.extension.incrementer.H2KeyGenerator"/>

简单调用示例:

声明Mapper
com.quickstart.mapper.UserMapper">
    selectMaxAge" resultType="java.lang.Integer">
        select max(age) from person
    
 
@Mapper
public interface UserMapper extends BaseMapper {Integer selectMaxAge();}
 
执行Mapper
@Resource
private UserMapper userMapper;
 
@Test
public void testSelect() {
    List userList = userMapper.selectList(null);
    Integer integer = userMapper.selectMaxAge();
}

 

声明Server
@Service
public interface UserServer extends IService {List listAll();}
 
@Service
public class UserServerImpl extends ServiceImpl<UserMapper , User> implements UserServer {
    @Resource
    CustomMapper customMapper;
 
    @Override
    public List listAll() {
        return customMapper.selectList(null);
    }
}
 
执行Service
@Autowired
UserServer userServer;
 
public List test() {
    userServer.selectList(null);
    userServer.listAll();
}

代码生成器简介

MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:添加 代码生成器 依赖
    com.baomidou
    mybatis-plus-generator
    3.3.1.tmp
#Velocity(默认)
添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。
 
<dependency>
    org.apache.velocity
    velocity-engine-core
    2.2
dependency>
#Freemarker
<dependency>
    org.freemarker
    freemarker
    2.3.30
dependency>
#Beetl
<dependency>
    com.ibeetl
    beetl
    3.1.3.RELEASE
dependency>

 

// 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //当前文件夹
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/mybatis-plus-sample-generator/src/main/java");
        gc.setAuthor("Arnold");
//        实体类是否添加Swagger2注解
//        gc.setSwagger2(true);
        gc.setOpen(false);
        //默认不覆盖,如果文件存在,将不会再生成,配置true就是覆盖
        gc.setFileOverride(true);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/activity?characterEncoding=utf8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.baomidou.mybatisplus.samples.generator");
        mpg.setPackageInfo(pc);
        // 自定义属性注入
        InjectionConfig cfg = new InjectionConfig() {
             @Override public void initMap() { // to do nothing}
        };
        List focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath "/mybatis-plus-sample-generator/src/main/resources/mapper/" pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
       } });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("com.xxx.BaseEntity") 实体类的父类没有则不写;
        strategy.setEntityLombokModel(true);
//        strategy.setSuperControllerClass("com.xxx.BaseController")Controller的父类没有则不写;
        strategy.setInclude(scanner("表名"));
        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
 
public static String scanner(String tip) {
    Scanner scanner = new Scanner(System.in);
    StringBuilder help = new StringBuilder();
    help.append("请输入+ tip + "");
    System.out.println(help.toString());
    if (scanner.hasNext()) {
        String ipt = scanner.next();
        if (StringUtils.isNotEmpty(ipt)) {
            return ipt;
        }
    }
    throw new MybatisPlusException("请输入正确的+ tip + "");
}

 

你可能感兴趣的:(海豚湾的等待)