自动代码生成 项目结构预览:
项目搭建:
- 环境配置
- 新建项目
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的报错等级:
扫描二维码关注公众号,回复: 12707586 查看本文章
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); } }