自動代碼生成 項目結構預覽:
項目搭建:
- 環境配置
- 新建項目
pom.xml配置:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.company</groupId> <artifactId>springbootmybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springbootmybatis</name> <description>Demo project for Spring Boot</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.2</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!--分頁插件使用方式一--> <!--<dependency>--> <!--<groupId>com.github.pagehelper</groupId>--> <!--<artifactId>pagehelper</artifactId>--> <!--<version>4.0.0</version>--> <!--</dependency>--> <!--分頁插件使用方式二--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.33</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> </build> </project>
application.yml配置:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver name: Mysql url: jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: root # 使用druid數據源 type: com.alibaba.druid.pool.DruidDataSource filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 ## 該配置節點爲獨立的節點,有很多同學容易將這個配置放在spring的節點下,導致配置無法被識別 mybatis: mapper-locations: classpath:mapping/*.xml #注意:一定要對應mapper映射xml文件的所在路徑 type-aliases-package: com.company.springbootmybatis.model # 注意:對應實體類的路徑 #pagehelper分頁插件 pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql
mybatis-generator.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 引入配置文件 application.yml配置文件引入失敗 獲取不到配置信息 application.properties配置文件未測試--> <!-- <properties resource="application.yml"/>--> <!-- 數據庫驅動:選擇你的本地硬盤上面的數據庫驅動包--> <classPathEntry location="D:\TEST_repository\mysql\mysql-connector-java\8.0.20\mysql-connector-java-8.0.20.jar"/> <context id="Mysql" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--yml配置獲取不到遂將數據庫鏈接URL,用戶名、密碼複製此處--> <!-- <jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}">--> <!--數據庫鏈接URL,用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC" userId="root" password="root"> <property name="useInformationSchema" value="true"/> <property name="remarks" value="true"/> </jdbcConnection> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.company.springbootmybatis.model" targetProject="src/main/java"> <!-- 是否在當前路徑下新加一層schema,eg:fase路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false"/> <!-- 是否針對string類型的字段在set的時候進行trim調用,就是去空格 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.company.springbootmybatis.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名--> <table tableName="book_test" domainObjectName="BookTest" mapperName="BookTestMapper"></table> </context> </generatorConfiguration>
com.mysql.cj.jdbc.Driver 驅動問題:
mysql-connector-java 版本用的8.0.20 此處 driverClass 應配置爲 com.mysql.cj.jdbc.Driver 而非 com.mysql.jdbc.DriverCaused by: java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized
connectionURL初始配置jdbc:mysql://127.0.0.1:3306/book
配置修改爲:jdbc:mysql://localhost:3306/spring?serverTimezone=UTC
有多個params的時候需要以&分開,但&要改爲&
jdbc:mysql://127.0.0.1:3306/book?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
代碼生成:
啓動類:
@MapperScan:
@SpringBootApplication @MapperScan("com.company.springbootmybatis.mapper") public class SpringbootmybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootmybatisApplication.class, args); } }
若出現 mapper注入失敗 的解決辦法:
降低IDEA的報錯等級:
Controller:
分頁: PageHelper.startPage(pageNum, pageSize);
@RestController @RequestMapping("/book") public class BookTestCroll { @Autowired BookTestService bookTestService; @GetMapping("/get/{id}")//@PathVariable獲取路徑數據 private String get(@PathVariable Integer id) { return JSON.toJSONString(bookTestService.get(id)); } @GetMapping("/getAll")//@RequestParam 獲取key=value數據 private String getAll(@RequestParam Integer pageNum, @RequestParam Integer pageSize) { PageHelper.startPage(pageNum, pageSize); Page<BookTest> all = bookTestService.getAll(1); return JSON.toJSONString(all); } }
PageHelpere的使用方式二:
引入依賴:
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.0.0</version> </dependency>
注入pagehelper 未測試:
@Bean PageHelper pageHelper(){ //分頁插件 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("reasonable", "true"); properties.setProperty("supportMethodsArguments", "true"); properties.setProperty("returnPageInfo", "check"); properties.setProperty("params", "count=countSql"); pageHelper.setProperties(properties); //添加插件 new SqlSessionFactoryBean().setPlugins(new Interceptor[]{pageHelper}); return pageHelper; }
Service:
多條件查詢:xxxExample的使用
分頁返回值:Page<T>
@Service public class BookTestServiceImp implements BookTestService { @Autowired BookTestDao bookTestDao; @Override public BookTest get(Integer id) { return bookTestDao.selectByPrimaryKey(id); } @Override public Page<BookTest> getAll(Integer id) { BookTestExample bookTestExample = new BookTestExample(); bookTestExample.createCriteria().andIdGreaterThanOrEqualTo(id); bookTestExample.setOrderByClause("id DESC"); return bookTestDao.selectByExample(bookTestExample); } }