<!--jdbc--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--mysql数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> 复制代码
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/spring_practice?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8 username: spring-practice password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver 复制代码
<!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> 复制代码
springboot的应用配置文件application.yml中配置mybaits “*Mapper.xml”文件(sql都写到这些文件中)的位置
mybatis: mapper-locations: classpath:/mybatis/mapper/*.xml 复制代码
在任意一个被@Configuration(@SpringBootApplication被@Configuration注解)注解的类上添加@MapperScan,指定mybaits的dao类所在的package
@SpringBootApplication(scanBasePackages = {"com.huang.*"}) @MapperScan({"com.huang.spring.practice"}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } 复制代码
使用mybatis来操作数据库的时,我们还需要创建dto、dao、*Mapper.xml文件。如果手动创建上述文件的话,那将会非常的麻烦!!!好在人民的智慧是无穷的,我们可以通过mybatis-generator插件来帮我们自动生成指定数据库表的dto、dao、*Mapper.xml。整合和使用mybaits-generator的步骤如下:
pom文件<build/>元素的<plugins/>下添加一个新的<plugin/>元素,来配置mybatis-generator插件的相关配置:
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.4.0</version> <configuration> <!-- mybatis-generator用于自动生成代码的配置文件 --> <configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile> <verbose>true</verbose> <!-- 允许覆盖同名的文件 --> <overwrite>true</overwrite> </configuration> <!-- 配置JDBC驱动 --> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> </dependencies> </plugin> 复制代码
CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` smallint(6) NOT NULL, `city` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 复制代码
<?xml version="1.0" encoding="UTF-8" ?> <!--mybatis的代码生成器相关配置--> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 引入配置文件 --> <!-- 一个数据库一个context,context的子元素必须按照它给出的顺序 property*,plugin*,commentGenerator?,jdbcConnection,javaTypeResolver?, javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+ --> <context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat"> <!-- 这个插件给生成的Java模型对象增加了equals和hashCode方法 --> <!--<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>--> <!-- 注释 --> <commentGenerator> <!-- 是否不生成注释 --> <property name="suppressAllComments" value="true"/> <!-- 不希望生成的注释中包含时间戳 --> <!--<property name="suppressDate" value="true"/>--> <!-- 添加 db 表中字段的注释,只有suppressAllComments为false时才生效--> <!--<property name="addRemarkComments" value="true"/>--> </commentGenerator> <!-- jdbc连接 --> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/spring_practice?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8" userId="spring-practice" password="123456"> <!--高版本的 mysql-connector-java 需要设置 nullCatalogMeansCurrent=true--> <property name="nullCatalogMeansCurrent" value="true"/> </jdbcConnection> <!-- 类型转换 --> <javaTypeResolver> <!--是否使用bigDecimal,默认false。 false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal--> <property name="forceBigDecimals" value="true"/> <!--默认false false,将所有 JDBC 的时间类型解析为 java.util.Date true,将 JDBC 的时间类型按如下规则解析 DATE -> java.time.LocalDate TIME -> java.time.LocalTime TIMESTAMP -> java.time.LocalDateTime TIME_WITH_TIMEZONE -> java.time.OffsetTime TIMESTAMP_WITH_TIMEZONE -> java.time.OffsetDateTime --> <!--<property name="useJSR310Types" value="false"/>--> </javaTypeResolver> <!-- 生成实体类地址 --> <javaModelGenerator targetPackage="com.huang.spring.practice.user.dto" targetProject="src/main/java"> <!-- 是否让 schema 作为包的后缀,默认为false --> <!--<property name="enableSubPackages" value="false"/>--> <!-- 是否针对string类型的字段在set方法中进行修剪,默认false --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成Mapper.xml文件 --> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources/mybatis/mapper"> <!--<property name="enableSubPackages" value="false"/>--> </sqlMapGenerator> <!-- 生成 XxxMapper.java 接口--> <javaClientGenerator targetPackage="com.huang.spring.practice.user.dao" targetProject="src/main/java" type="XMLMAPPER"> <!--<property name="enableSubPackages" value="false"/>--> </javaClientGenerator> <!-- schema为数据库名,oracle需要配置,mysql不需要配置。 tableName为对应的数据库表名 domainObjectName 是要生成的实体类名(可以不指定,默认按帕斯卡命名法将表名转换成类名) enableXXXByExample 默认为 true, 为 true 会生成一个对应Example帮助类,帮助你进行条件查询,不想要可以设为false --> <!-- 给我们刚刚创建的user表自动生成dto、dao、mapper.xml--> <table schema="" tableName="user" domainObjectName="User" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false" selectByExampleQueryId="false"> <!--是否使用实际列名,默认为false--> <!--<property name="useActualColumnNames" value="false" />--> </table> </context> </generatorConfiguration> 复制代码
mvn mybatis-generator:generate 复制代码
D:/JAVA/GIT/spring-practice>mvn mybatis-generator:generate [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building spring.practice 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- mybatis-generator-maven-plugin:1.4.0:generate (default-cli) @ spring.practice --- [INFO] Connecting to the Database [INFO] Introspecting table user [INFO] Generating Record class for table user [INFO] Generating Mapper Interface for table user [INFO] Generating SQL Map for table user [INFO] Saving file UserMapper.xml [INFO] Saving file User.java [INFO] Saving file UserMapper.java [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.010 s [INFO] Finished at: 2020-07-12T12:06:26+08:00 [INFO] Final Memory: 21M/217M [INFO] ------------------------------------------------------------------------ 复制代码
package com.huang.spring.practice.user.controller; import com.huang.spring.practice.user.dao.UserMapper; import com.huang.spring.practice.user.dto.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * User controller层 */ @RestController @RequestMapping("/api/user/") public class UserController { @Autowired private UserMapper userMapper; /** * 根据用户id查询用户信息 * * @param id * @return */ @GetMapping("/getUserInfo/{id}") public User getUserInfo(@PathVariable("id") Long id) { return userMapper.selectByPrimaryKey(id); } } 复制代码
insert into user (name, age, city) values ('小明', '18', '深圳'); mysql> select * from user; +----+--------+-----+--------+ | id | name | age | city | +----+--------+-----+--------+ | 1 | 小明 | 18 | 深圳 | +----+--------+-----+--------+ 1 row in set (0.00 sec) 复制代码