您好,登錄后才能下訂單哦!
如何在SpringBoot中使用MybatisPlus?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
springboot一種全新的編程規范,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程,SpringBoot也是一個服務于框架的框架,服務范圍是簡化配置文件。
項目目錄結構:
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-->StudentMapper.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 { }
經過以上六步項目已經搭建完成,下面就是寫業務代碼了,只需要實現controller即可,下面對StudentController.java進行修改:
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"; } }
看完上述內容,你們掌握如何在SpringBoot中使用MybatisPlus的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。