文章目录
1、创建SpringBoot工程
本示例项目代码下载地址:
https://download.csdn.net/download/mouday/12662948
使用Spring Initializer创建SpringBoot工程,只用如下依赖
Web MySQL MyBatis
2、项目结构
$ tree . ├── pom.xml └── src └── main ├── java │ └── com │ └── mouday │ └── demo │ ├── Application.java │ ├── controller │ │ └── PersonController.java │ ├── mapper │ │ ├── PersonMapper.java │ │ └── PersonMapper.xml │ ├── pojo │ │ └── Person.java │ └── service │ ├── PersonService.java │ └── impl │ └── PersonServiceImpl.java └── resources ├── application.yml ├── generator │ └── generatorConfig.xml ├── sql │ └── person.sql ├── static └── templates
3、配置文件
3个配置文件和1个建表语句文件
pom.xml # 项目依赖 application.yml # 项目配置 generatorConfig.xml # 自动代码生成配置 person.sql # 建表语句
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.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.mouday</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <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.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <!-- 数据库连接 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--使用durid连接池的依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.1</version> </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> <resources> <!--编译src/main/java目录下的xml文件--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> <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>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <!-- 依赖 --> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
application.yml
# 设置端口 server: port: 8080 # 设置数据源 spring: datasource: url: jdbc:mysql://localhost:3306/data username: root password: 123456 # 连接池类型 type: com.alibaba.druid.pool.DruidDataSource # 驱动 driver-class-name: com.mysql.cj.jdbc.Driver # 连接池配置 druid: # 最小数 min-idle: 5 # 最大数 max-active: 20 # 初始大小 initial-size: 5 # 配置获取连接等待超时时间 max-wait: 6000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 time-between-eviction-runs-millis: 60000 # 配置一个连接在池中最小生存时间 单位为毫秒 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false # 打开 PSCache,并且指定每个连接上PSCache的大小 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,wall用于防火墙 filters: stat,wall # 配置mybatis mybatis: # mapper-locations: classpath:mappers/*.xml # 全局的映射,不用在xml文件写实体类的全路径 # type-aliases-package: com.mouday.demo.pojo configuration: # 开启驼峰映射 map-underscore-to-camel-case: true
generatorConfig.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> <context id="default" targetRuntime="MyBatis3"> <!--创建class时,对注释进行控制--> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- jdbc的数据库连接 --> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/data" userId="root" password="123456"> </jdbcConnection> <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制 --> <javaTypeResolver> <!-- 是否使用BigDecimals,false可自动转化以下类型(Long Integer Short等) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- Model模型生成器--> <javaModelGenerator targetPackage="com.mouday.demo.pojo" targetProject="src/main/java"> <!--是否允许子包,即targetPackage.schemaName.tableName--> <property name="enableSubPackages" value="true"/> <!-- 是否对类CHAR类型的列的数据进行trim操作 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- Mapper映射文件的包名和位置--> <sqlMapGenerator targetPackage="com.mouday.demo.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 客户端代码--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.mouday.demo.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> <table tableName="person" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>
person.sql
CREATE TABLE `person` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` int(11) DEFAULT NULL )
4、执行代码生成
$ mvn mybatis-generator:generate
生成3个文件
Person.java # model PersonMapper.java # mapper接口 PersonMapper.xml # sql映射
Person.java
package com.mouday.demo.pojo; public class Person { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
PersonMapper.java
package com.mouday.demo.mapper; import com.mouday.demo.pojo.Person; public interface PersonMapper { int deleteByPrimaryKey(Integer id); int insert(Person record); int insertSelective(Person record); Person selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Person record); int updateByPrimaryKey(Person record); }
PersonMapper.xml
<?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.mouday.demo.mapper.PersonMapper"> <resultMap id="BaseResultMap" type="com.mouday.demo.pojo.Person"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <sql id="Base_Column_List"> id, name, age </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from person where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from person where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.mouday.demo.pojo.Person"> insert into person (id, name, age ) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER} ) </insert> <insert id="insertSelective" parameterType="com.mouday.demo.pojo.Person"> insert into person <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="name != null"> name, </if> <if test="age != null"> age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="name != null"> #{name,jdbcType=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.mouday.demo.pojo.Person"> update person <set> <if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.mouday.demo.pojo.Person"> update person set name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
5、Service和Controller
对外服务接口
PersonService.java # 接口 PersonServiceImpl.java # 实现 PersonController.java # 控制器
PersonService.java
package com.mouday.demo.service; import com.mouday.demo.pojo.Person; public interface PersonService { int deleteByPrimaryKey(Integer id); int insert(Person record); int insertSelective(Person record); Person selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Person record); int updateByPrimaryKey(Person record); }
PersonServiceImpl.java
package com.mouday.demo.service.impl; import com.mouday.demo.mapper.PersonMapper; import com.mouday.demo.pojo.Person; import com.mouday.demo.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PersonServiceImpl implements PersonService { @Autowired private PersonMapper personMapper; @Override public int deleteByPrimaryKey(Integer id) { return personMapper.deleteByPrimaryKey(id); } @Override public int insert(Person record) { return personMapper.insert(record); } @Override public int insertSelective(Person record) { return personMapper.insertSelective(record); } @Override public Person selectByPrimaryKey(Integer id) { return personMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(Person record) { return personMapper.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(Person record) { return personMapper.updateByPrimaryKey(record); } }
PersonController.java
package com.mouday.demo.controller; import com.mouday.demo.pojo.Person; import com.mouday.demo.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/person") public class PersonController { @Autowired private PersonService personService; @GetMapping("/selectByPrimaryKey") public Person selectByPrimaryKey(Integer id){ return personService.selectByPrimaryKey(id); } }
6、运行启动
package com.mouday.demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication @MapperScan("com.mouday.demo.mapper") // 指定mapper扫描包 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @GetMapping("/") public String index(){ return "hello"; } }
请求和返回结果
GET http://localhost:8080/person/selectByPrimaryKey?id=1 { id: 1, name: "刘禅", age: 26 }
参考
SpringBoot集成MyBatis及使用mybatis-generator-plugin生成代码(完美,步骤巨详细)