IDEA搭建SpringBoot2.X整合Mybatis(含generator实体映射)
本篇文章将教你使用 IDEA工具 搭建 SpringBoot(2.x)并整合 Mybatis
先来统一环境 :
- IDEA------2019.1.2
- JDK---------1.8
- MAVEN-----3.3.9
- SpringBoot----2.1.9稳定版(IDEA工具默认
第一部分,新建项目:
step1.1
step1.2
点击《下一步》到step1.3:
step1.4:这一步我们创建一个SpringBoot 2.1.9的WEB项目
来到SQL选项,勾选MYSQL/JDBC驱动/以及MyBatis,这里我只选最基本的功能做DEMO。如需其他可自行添加
step1.5:点击完《下一步》,然后finish,至此。项目创建完成。目录结构如下:
POM文件内容:
<?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.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.pic</groupId>
<artifactId>test-springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test-springboot-mybatis</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-jdbc</artifactId>
</dependency>
<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.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
此时启动应用,控制台会提示没有配置数据源(如图)
第二部分 配置!
step2.1 我们采用SpringBoot2.X推荐的YML文件方式(yml文件最终也会被解析为properties)
在src/main/resource文件夹下新建 application.yml配置文件,内容如下:
server:
port: 8080 #指定项目启动端口号
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/testdb?serverTimezone=UTC
username: root
password: 123123
#较早版本使用的是:com.mysql.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml #此处为Mybatis的Mapper.xml文件路径
type-aliases-package: com.pic.test.entity # 此处为实体Bean的路径
#以上两个路径暂时没有。我们使用工具根据数据库生成,暂定以上路径
testdb是数据库名、?serverTimezone=UTC 是因为 时区会报乱码 才加的
至此 项目已经可以启动。
第三部分 使用 generator 根据数据库表生成实体
先来看我的数据库表结构,简单起见,只有3个字段做demo,方便~
step3.1 在pom.xml中添加 mybatis generator 自动生成代码插件。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
step3.2 于resource文件夹下创建generator文件夹,并在文件夹中创建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>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="E:\apache-maven-file\mysql\mysql-connector-java\8.0.17\mysql-connector-java-8.0.17.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库连接驱动类,URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/testdb?serverTimezone=UTC" userId="root" password="123123">
<!--避免生产UserKey 和 UserWithBlobs-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成(实体)模型的包名和位置-->
<javaModelGenerator targetPackage="com.pic.test.entity" targetProject="src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成XML映射文件的包名和位置-->
<sqlMapGenerator targetPackage="resources.mapper" targetProject="src\main">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO接口的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.pic.test.mapper" targetProject="src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
step3.3启动generator插件,生成 实体Bean、Mapper 和 mapper接口
点击 “加号” 选择MAVEN
如图,Command line 输入 mybatis-generator:generate 命令
点击OK,运行maven依赖
控制台这里显示已经生成了我们的各种文件
User实体:
package com.pic.test.entity;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
}
UserMapper接口
package com.pic.test.mapper;
import com.pic.test.entity.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
UserMapper.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.pic.test.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.pic.test.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, username, password
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.pic.test.entity.User" >
insert into user (id, username, password
)
values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.pic.test.entity.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="username != null" >
username,
</if>
<if test="password != null" >
password,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="username != null" >
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.pic.test.entity.User" >
update user
<set >
<if test="username != null" >
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.pic.test.entity.User" >
update user
set username = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
第四部分 测试
step4.1给数据库添加一些信息,编辑UserMapper接口 添加一个查询所有数据的方法:getUser,以及两个注解
@Mapper
@Component
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> getUser();
}
step4.2 修改UserMapper.xml 添加对应语句部分
<select id="getUser" resultType="com.pic.test.entity.User">
select * from user
</select>
新建controller包,新建UserController 在其中添加如下代码
@Controller
public class UserController {
@Autowired
UserService userService;
@ResponseBody
@RequestMapping("/gu")
public List<User> getUser(){
return userService.grtUser();
}
}
新建service包,新建UserService 在其中添加如下代码和注解
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public List<User> grtUser(){
List<User> user = userMapper.getUser();
return user;
}
}
此时,项目结构如下:
此时,我们启动项目,在浏览器输入“http://localhost:8080/gu”可以看到,数据返回
采坑问题集合:采坑问题集合:采坑问题集合:
Q1.生成代码时候报错:
A1这个问题是代码生成插件导致的,其数据库url访问地址是走的自身 generatorConfig.xml 配置文件,在其中的url后加上
?serverTimezone=UTC 即可(如图)
----------------------------------------------------------------------------------------------------------------------------------------------
Q2 生成的数据库表带有 UserKey 和 UserWithBlobs的Bean...#¥%……&反正生成的不对!
A1 生成的数据库表如果是user的有可能会生成其系统表的User,即生成带有带有 UserKey 和 UserWithBlobs的Bean,为了避免这种情况,可以在generator.xml中<jdbcConnection>标签下 添加<property name="nullCatalogMeansCurrent" value="true"/>
----------------------------------------------------------------------------------------------------------------------------------------------
Q3 生成时候提示路径报错
A3 generator 生成文件的路径并不是application.properties中那两个,而是在generatorConfig.xml 自己的配置文件中配置的,注意下图画圈的地方~你找到规律了吗?
之后的文章我将会陆续更新
《多数据源版》
《整合SpringData JPA 》
《整合Redis》
《整合rabbitMQ》
《整合LOG与其他插件》~敬请期待~
上一篇: Java去掉空格换行符回车的方法
下一篇: 第五章 数组