此项目使用idea用Spring Initializr快速搭建,不含service和controller层,使用单元测试试通数据库查询
0)准备数据库表
数据库执行下面语句,创建d_user表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for d_user
-- ----------------------------
DROP TABLE IF EXISTS `d_user`;
CREATE TABLE `d_user` (
`id` int(0) NOT NULL,
`name` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`ip` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of d_user
-- ----------------------------
INSERT INTO `d_user` VALUES (1001, '雨欣', '100011');
INSERT INTO `d_user` VALUES (1002, '雨欣:324:324:324', '100012');
SET FOREIGN_KEY_CHECKS = 1;
如下:
1)创建Spring Initializr
鼠标选择:file>new>project...进入创建菜单
选择Spring Initializr 修改配置值并next
随后选择你想用的功能,本人在pom文件中添加的,此处直接略过finish
创建后结构如下:
2)mybatis-gennerator生成dao,mapper
项目生成后配置pom文件,引入需要的依赖:在pom文件的build下添加如下代码:
<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.2</version>
<configuration>
<configurationFile>
src/main/resources/generator/genteratorCongfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
</plugin>
</plugins>
<!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
更新pom依赖加载,在resources文件夹下添加generator文件夹,并创建config.properties;genteratorCongfig.xml;
代码直接粘贴如下:
其中config.properties文件内容如下,注意修改你的数据库配置,自动生成的mapper,dao子文件夹名称,以及生成路径
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true
jdbc.user=root
jdbc.password=root
#??槊?moduleName=d_user
#表名
tableName=d_user
#默认路径
modelPath=com.example.demo1
其中genteratorCongfig.xml 文件内容如下
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<properties resource="generator/config.properties"/>
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
<property name="caseSensitive" value="true"/>
<property name="lombok" value="Getter,Setter,ToString"/>
</plugin>
<jdbcConnection driverClass="${jdbc.driverClass}"
connectionURL="${jdbc.url}"
userId="${jdbc.user}"
password="${jdbc.password}">
</jdbcConnection>
<!--实体-->
<javaModelGenerator targetPackage="${modelPath}.model.entity.${moduleName}"
targetProject="src/main/java"/>
<!--mapper.xml-->
<sqlMapGenerator targetPackage="mapper.${moduleName}"
targetProject="./src/main/resources"/>
<!--mapper接口-->
<javaClientGenerator targetPackage="${modelPath}.dao.${moduleName}"
targetProject="src/main/java"
type="XMLMAPPER"/>
<!--为哪张表生成代码-->
<table tableName="${tableName}">
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
</context>
</generatorConfiguration>
随后双击序号3处,等待自动生成组件,生成mapper;dao;model如下
打开生成文件,此时pom未引入相关依赖,方法报错:
再次打开pom文件,配置如下内容:(包括了测试单元)
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
解决报错
3)创建查询语句
创建application.yml,mybatis-config.xml文件如下:
application文件内容如下:
spring:
application:
name: springboot-mybatis
# profiles:
# active: test
datasource:
#MySQL数据库支持配置
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true
username: root
password: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimum-idle: 5
maximum-pool-size: 100
idle-timeout: 600000
pool-name: OrderHikariCP
max-lifetime: 1800000
connection-timeout: 60000
connection-test-query: SELECT 1
server:
port: 8088
mybatis:
config-location: classpath:mybatis-config.xml
type-aliases-package: org.example.common.dao.**
mapper-locations: classpath:mapper/*/*.xml
dataType: 0
mybatis-config文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="application.yml">
<property name="dataType" value="${dataType}"/>
</properties>
<settings>
<!-- 在null时也调用 setter,适应于返回Map,3.2版本以上可用 -->
<setting name="callSettersOnNulls" value="true"/>
<!-- 全局映射器启用缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 查询时,关闭关联对象即时加载以提高性能 -->
<setting name="lazyLoadingEnabled" value="false"/>
<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
<setting name="multipleResultSetsEnabled" value="true"/>
<!-- 允许使用列标签代替列名 -->
<setting name="useColumnLabel" value="true"/>
<!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
<setting name="useGeneratedKeys" value="true"/>
<!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
<!--<setting name="autoMappingBehavior" value="FULL" />-->
<!-- 对于批量更新操作缓存SQL以提高性能 -->
<setting name="defaultExecutorType" value="SIMPLE"/>
<!-- 数据库超过25000秒仍未响应则超时 -->
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
</configuration>
随后在mapper中创建查询selectAllById方法:
DUser selectAllById(@Param("id") Integer id);
在mapper映射中添加查询语句:
注意:resultType若为java对象,地址映射对。
<sql id="User_Num">
id,name,ip
</sql>
<!--查询-->
<select parameterType="Integer" id="selectAllById" resultType="com.example.demo1.model.entity.d_user.DUser">
SELECT
<include refid="User_Num"/>
FROM d_user WHERE id = #{id}
</select>
再修改springboot启动项如下:
@ComponentScan(value = {"com.example"})
@MapperScan("com.example.demomybatis.**")
修改测试启动项如下:
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Demo1Application.class)
class Demo1ApplicationTests {
@Autowired(required=true)
DUserMapper dUserMapper;
@Test
void contextLoads() {
System.out.println("here==="+dUserMapper.selectAllById(1001).getName());
}
}
启动测试单元,查询成功。
注意:若重新逆向工程创建项目,需要删除mapper文件,不然累加,启动报错
进阶项目---搭建dubbo项目: http://08643.cn/p/be534104785b