spring boot + mybatis plus

1. spring boot 환경 구축
1. 뮤 직 비디오 의존 팩 추가
        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            org.projectlombok
            lombok
            true
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.0
        
        
        
            junit
            junit
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.4.0
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        

2. application. yml 설정 추가 (resources 디 렉 터 리 아래)
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

#Servlet    
server:
  port: 80
  servlet:
    context-path: /index

#    
logging:
  level:
    root: warn
    com.zimug.boot.launch.mapper: trace

2. mybatis - plus 환경 구축
mapper 스 캔 주석 추가: @ MapperScan ("자신의 mapper 경로 주소")
@SpringBootApplication
@MapperScan("com.example.my.app.user.mapper")
public class MyApplication {

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

}


(1).
Mapper.insert(bean);

(2). 수정
Bean user2 = Mapper.selectById(1);
user2.setTitle("test");
int result = Mapper.updateById(user2);

(3). 삭제
//  id    
int rows = userMapper.deleteById(1);
System.out.println("     :" + rows);
//    
Map map = new HashMap<>();
map.put("name","   ");
map.put("age",18);
//    
int rows = userMapper.deleteByMap(map);
System.out.println("     :" + rows);

(4). 조회
//          
User user = userMapper.selectById(1);
System.out.println(user);
//  ids      
List ids = Arrays.asList(
    1,
    2,
    3
);
List list = userMapper.selectBatchIds(ids);
list.forEach(System.out::println);

3. my batis - plus 코드 자동 생 성기
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 *    mybatis-plus          
 */
public class CodeGenerator {
    public static final String package_name = "com.example.my.app"; //        
    public static final String super_controller = "com.example.my.base.BaseController"; //        ,       !
    public static final String super_entity = "com.example.my.base.BaseEntity"; //"        ,       !"

    public static void main(String[] args) {
        //      
        AutoGenerator mpg = new AutoGenerator();
        String projectPath = System.getProperty("user.dir");
        /*     GlobalConfig*/
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        globalConfig.setAuthor("jobob");
        globalConfig.setOpen(false);
        mpg.setGlobalConfig(globalConfig);
        /*      DataSourceConfig*/
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("root");
        mpg.setDataSource(dataSourceConfig);
        //    
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("   "));
        pc.setParent(package_name); /*      */
        mpg.setPackageInfo(pc);

        //      
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                //      
            }
        };
        //         freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        //        
        List focList = new ArrayList<>();
        //            
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //          ,     Entity       、     xml           !!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + 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.setSuperEntityClass(super_entity);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //     
        strategy.setSuperControllerClass(super_controller);
        //           
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("  ,        ").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

    /**
     *        
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("   " + tip + ":");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("      " + tip + "!");
    }

}

좋은 웹페이지 즐겨찾기