SpringBoot+MybatisPlus+코드 생 성기 통합 예시

프로젝트 디 렉 터 리 구조:

pom 파일:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 
 <groupId>com.warrior</groupId>
 <artifactId>ETH</artifactId>
 <version>1.0-SNAPSHOT</version>
 
 <!-- Inherit defaults from Spring Boot -->
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.0.BUILD-SNAPSHOT</version>
 </parent>
 
 <!-- Add typical dependencies for a web application -->
 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <!-- mybatis orm   -->
  <dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatisplus-spring-boot-starter</artifactId>
   <version>1.0.4</version>
  </dependency>
 
  <dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus</artifactId>
   <version>2.0.7</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity -->
  <dependency>
   <groupId>org.apache.velocity</groupId>
   <artifactId>velocity</artifactId>
   <version>1.7</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
  <dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.28</version>
  </dependency>
 
 
  <!--     jdbc  -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
  </dependency>
  <!--mysql    -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
  </dependency>
  <!--  druid       -->
  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.1.9</version>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
  <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>0.10.1</version>
   <scope>provided</scope>
  </dependency>
 
 </dependencies>
 
 <!-- Package as an executable jar -->
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>
 
 <!-- Add Spring repositories -->
 <!-- (you don't need this if you are using a .RELEASE version) -->
 <repositories>
  <repository>
   <id>spring-snapshots</id>
   <url>http://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </repository>
  <repository>
   <id>spring-milestones</id>
   <url>http://repo.spring.io/milestone</url>
  </repository>
 </repositories>
 <pluginRepositories>
  <pluginRepository>
   <id>spring-snapshots</id>
   <url>http://repo.spring.io/snapshot</url>
  </pluginRepository>
  <pluginRepository>
   <id>spring-milestones</id>
   <url>http://repo.spring.io/milestone</url>
  </pluginRepository>
 </pluginRepositories>
</project>
Application

package com.warrior;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@SpringBootApplication
@MapperScan("com.warrior.mapper") //  mapper  
public class Application {
 
 public static void main(String[] args) throws Exception {
  SpringApplication.run(Application.class, args);
 }
}
application.properties

#          
spring.profiles.active=dev
#        
#spring.profiles.active=pro
application-dev.properties

server.port=8080
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/eth
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.cn.restyle.entity
프로필:
1).

package com.warrior.config;
 
import javax.sql.DataSource; 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
 
import com.alibaba.druid.pool.DruidDataSource;
 
/**
 *      
 */
@Configuration
public class DataSourceConfig {
 
 @Bean(name="dataSource")
 @ConfigurationProperties(prefix="spring.datasource")
 public DataSource dataSource(){
  return new DruidDataSource();
 }
 
 //        
 @Bean(name="transactionManager")
 public DataSourceTransactionManager transactionManager(){
  return new DataSourceTransactionManager(dataSource());
 }
 
}
2). MybatisPlusConfig.java:

package com.warrior.config;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
 
@Configuration
//  dao   Mapper  
@MapperScan("com.warrior.mapper*")
public class MybatisPlusConfig {
 /**
  * mybatis-plus     
  */
 
 @Bean
 public PaginationInterceptor paginationInterceptor(){
  PaginationInterceptor page = new PaginationInterceptor();
  page.setDialectType("mysql");
  return page;
 } 
}
코드 생 성:
1).mysql 데이터베이스 구축 표

2).코드 생 성기 MpGenenator.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 
/**
 * <p>
 *        
 * </p>
 */
public class MpGenerator {
 
 final static String dirPath = "D://";
 
 /**
  * <p>
  * MySQL     
  * </p>
  */
 public static void main(String[] args) {
  AutoGenerator mpg = new AutoGenerator();
  //    freemarker   ,   Veloctiy
  //mpg.setTemplateEngine(new FreemarkerTemplateEngine());
 
  //     
  GlobalConfig gc = new GlobalConfig();
  gc.setOutputDir(dirPath);
  gc.setAuthor("lqh");
  gc.setFileOverride(true); //    
  gc.setActiveRecord(true);//    ActiveRecord      false
  gc.setEnableCache(false);// XML     
  gc.setBaseResultMap(true);// XML ResultMap
  gc.setBaseColumnList(true);// XML columList
 
  //        ,   %s           !
  // gc.setMapperName("%sDao");
  // gc.setXmlName("%sMapper");
  // gc.setServiceName("MP%sService");
  // gc.setServiceImplName("%sServiceDiy");
  // gc.setControllerName("%sAction");
  mpg.setGlobalConfig(gc);
 
  //      
  DataSourceConfig dsc = new DataSourceConfig();
  dsc.setDbType(DbType.MYSQL);
  dsc.setTypeConvert(new MySqlTypeConvert(){
   //              【  】
   @Override
   public DbColumnType processTypeConvert(String fieldType) {
    System.out.println("    :" + fieldType);
    //   !!processTypeConvert         ,               、       。
    return super.processTypeConvert(fieldType);
   }
  });
  dsc.setDriverName("com.mysql.jdbc.Driver");
  dsc.setUsername("root");
  dsc.setPassword("123456");
  dsc.setUrl("jdbc:mysql://127.0.0.1:3306/eth?characterEncoding=utf8");
  mpg.setDataSource(dsc);
 
  //     
  StrategyConfig strategy = new StrategyConfig();
  // strategy.setCapitalMode(true);//        ORACLE   
  strategy.setTablePrefix(new String[] { "tb_", "tsys_" });//             
  strategy.setNaming(NamingStrategy.underline_to_camel);//       
  // strategy.setInclude(new String[] { "user" }); //       
  // strategy.setExclude(new String[]{"test"}); //       
  //        
  // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
  //      ,    
  // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
  //     mapper   
  // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
  //     service   
  // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
  //     service      
  // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
  //     controller   
  // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
  // 【  】        (   false)
  // public static final String ID = "test_id";
  // strategy.setEntityColumnConstant(true);
  // 【  】        (   false)
  // public User setName(String name) {this.name = name; return this;}
   strategy.setEntityBuilderModel(true);
  mpg.setStrategy(strategy);
 
  //    
  PackageConfig pc = new PackageConfig();
  pc.setParent("com");
  pc.setModuleName("warrior");
  pc.setController("controler");
  pc.setEntity("entity");
  pc.setMapper("mapper");
  pc.setService("service");
  pc.setServiceImpl("serviceImpl");
  pc.setXml("mapperXml");
 
  mpg.setPackageInfo(pc);
 
  //        ,    VM     cfg.abc 【  】
  InjectionConfig cfg = new InjectionConfig() {
   @Override
   public void initMap() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
    this.setMap(map);
   }
  };
 
  //     xxList.jsp   
  List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
/*  focList.add(new FileOutConfig("/template/list.jsp.vm") {
   @Override
   public String outputFile(TableInfo tableInfo) {
    //          
    return "D://my_" + tableInfo.getEntityName() + ".jsp";
   }
  });
  cfg.setFileOutConfigList(focList);
  mpg.setCfg(cfg);*/
 
  //    xml       
/*  focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
   @Override
   public String outputFile(TableInfo tableInfo) {
    return dirPath + tableInfo.getEntityName() + "Mapper.xml";
   }
  });
  cfg.setFileOutConfigList(focList);
  */
  mpg.setCfg(cfg);
 
  //      xml   ,          
/*  TemplateConfig tc = new TemplateConfig();
  tc.setXml(null);
  mpg.setTemplate(tc);*/
 
  //        ,   copy    mybatis-plus/src/main/resources/templates       ,
  //         src/main/resources/templates    ,            ,          
  // TemplateConfig tc = new TemplateConfig();
  // tc.setController("...");
  // tc.setEntity("...");
  // tc.setMapper("...");
  // tc.setXml("...");
  // tc.setService("...");
  // tc.setServiceImpl("...");
  //                OR Null        。
  // mpg.setTemplate(tc);
 
  //     
  mpg.execute();
 
  //       【  】
  System.err.println(mpg.getCfg().getMap().get("abc"));
 } 
}
생 성 된 파일 은 다음 과 같 습 니 다.해당 파일 을 프로젝트 대응 패키지 에 복사 하면 됩 니 다.

다음은 대응 하 는 종 류 를 보 여 줍 니 다.
.entity-->Student.java

package com.warrior.entity;
 
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
 
/**
 * <p>
 * 
 * </p>
 *
 * @author lqh
 * @since 2018-05-25
 */
@TableName("tb_student")
public class Student extends Model<Student> {
 
 private static final long serialVersionUID = 1L;
 
	@TableId(value="id", type= IdType.AUTO)
	private Integer id;
	@TableField("stu_name")
	private String stuName;
	@TableField("stu_number")
	private String stuNumber;
	private Integer age;
 
 
	public Integer getId() {
		return id;
	}
 
	public Student setId(Integer id) {
		this.id = id;
		return this;
	}
 
	public String getStuName() {
		return stuName;
	}
 
	public Student setStuName(String stuName) {
		this.stuName = stuName;
		return this;
	}
 
	public String getStuNumber() {
		return stuNumber;
	}
 
	public Student setStuNumber(String stuNumber) {
		this.stuNumber = stuNumber;
		return this;
	}
 
	public Integer getAge() {
		return age;
	}
 
	public Student setAge(Integer age) {
		this.age = age;
		return this;
	}
 
	@Override
	protected Serializable pkVal() {
		return this.id;
	}
 
}
.mapper-->StudentMapper.java

package com.warrior.mapper;
 
import com.warrior.entity.Student;
import com.baomidou.mybatisplus.mapper.BaseMapper;
 
/**
 * <p>
 * Mapper   
 * </p>
 *
 * @author lqh
 * @since 2018-05-25
 */
public interface StudentMapper extends BaseMapper<Student> {
 
}
mapperXml-->Student Mapper.xml(이 파일 은 src/main/resources/mapper 에 넣 어야 합 니 다)

<?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.warrior.mapper.StudentMapper">
 
	<!--          -->
	<resultMap id="BaseResultMap" type="com.warrior.entity.Student">
		<id column="id" property="id" />
		<result column="stu_name" property="stuName" />
		<result column="stu_number" property="stuNumber" />
		<result column="age" property="age" />
	</resultMap>
 
 <!--         -->
 <sql id="Base_Column_List">
  id, stu_name AS stuName, stu_number AS stuNumber, age
 </sql>
 
</mapper>
.service-->IStudentService.java

package com.warrior.service;
 
import com.warrior.entity.Student;
import com.baomidou.mybatisplus.service.IService;
 
/**
 * <p>
 *    
 * </p>
 *
 * @author lqh
 * @since 2018-05-25
 */
public interface IStudentService extends IService<Student> {
	
}
.serviceImpl-->StudentServiceImpl.java

package com.warrior.serviceImpl;
 
import com.warrior.entity.Student;
import com.warrior.mapper.StudentMapper;
import com.warrior.service.IStudentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
 
/**
 * <p>
 *      
 * </p>
 *
 * @author lqh
 * @since 2018-05-25
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
	
}
.controler-->StudentController.java 

package com.warrior.controler;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
/**
 * <p>
 *      
 * </p>
 *
 * @author lqh
 * @since 2018-05-25
 */
@Controller
@RequestMapping("/warrior/student")
public class StudentController {
	
}
상기 6 단계 프로젝트 를 통 해 이미 구축 되 었 습 니 다.다음은 업무 코드 를 쓰 는 것 입 니 다.contrller 만 실현 하면 됩 니 다.다음은 Student Controller.자바 에 대해 수정 하 겠 습 니 다.

package com.warrior.controler;
 
import com.warrior.entity.Student;
import com.warrior.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
/**
 * <p>
 *      
 * </p>
 *
 * @author lqh
 * @since 2018-05-05
 */
@Controller
@RequestMapping("/warrior/student")
public class StudentController {
 @Autowired
 IStudentService iStudentService;
 
 @RequestMapping("/hello")
 @ResponseBody
 public String hello() {
  //insert
  Student student = new Student()
    .setStuName("zhangsan")
    .setStuNumber("54")
    .setAge(23);
  boolean res = iStudentService.insert(student);
 
  return res ? "success" : "fail";
 }
}
프로젝트 실행,직접 방문,해결!!
프로젝트 github 주소:https://github.com/LinQiHong66/SpringBoot_MybatisPlus.git
mybatisPlus 홈 페이지:http://mp.baomidou.com/
SpringBoot+MybatisPlus+코드 생 성기 통합 예제 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 SpringBoot MybatisPlus 코드 생 성기 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 바 랍 니 다!

좋은 웹페이지 즐겨찾기