官网入门
http://www.mybatis.org/mybatis-3/zh/index.html
目录
4 配置mybatis generator 自动生成代码插件
配置pom.xml中generator 插件所对应的配置文件
5. SpringBoot启动类加注解@MapperScan
http://www.mybatis.org/mybatis-3/zh/getting-started.html
https://github.com/mybatis/mybatis-3
Spring领域其中最好用的莫过于SpringBoot,感觉很强大的,把以前ssm和ssh的那套集成配置一网打尽,进入主题,直接分享案例搭建全流程。
本项目使用的环境:
开发工具:Intellij IDEA 2018.1.5 springboot2.0.3
jdk:1.8.
maven:3.5.2 mysql8.0.13
额外功能
mybatis generator 自动生成代码插件
mysql数据库创建表并插入数据
我们先创建一个表user_info(表名不要为user这类容易误导数据库的名称,否则后期generator自动生成代码会遇到好多问题)
数据库工具SQLyog 很好用
CREATE TABLE user_info
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
插入数据
INSERT INTO user_info (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
步骤:
1.创建一个springboot项目:
完成后未改动的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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>mybatis_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatis_demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<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>1.3.2</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>
2 修改pom文件
1 首先咱们建立工程用的sping boot为2.0.7 .从我的截图和pom文件上看出
因为笔者建立工程时spring boot包一直拉不下来所以版本改为2.0.3.RELEASE
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
2 因为我用的mysql为8的版本,所以修改一下mysql的依赖版本
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
<scope>runtime</scope>
</dependency>
3 mybatis.generator 插件
依赖
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
插件
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
完成后刷新一下pom
工程目录如下
3、application添加相关配置
本案例不使用application.properties文件 而使用更加简洁的application.yml文件。
将resource文件夹下原有的application.properties文件改为application.yml
(备注:其实SpringBoot底层会把application.yml文件解析为application.properties), 文件的内容如下(此处只配置最基本的)
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
username: root
password: 12345678
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml
type-aliases-package: com.example.mybatis_demo.po
springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对于开发人员不用管,直接拿来使用即可。
4 配置mybatis generator 自动生成代码插件
配置pom.xml中generator 插件所对应的配置文件
${basedir}/src/main/resources/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="F:\repository\mysql\mysql-connector-java\8.0.13\mysql-connector-java-8.0.13.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:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT" userId="root" password="12345678">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.example.mybatis_demo.po" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mybatis_demo.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="user_info" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
注意 1
generatorConfig.xml的头文件http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd标红原因:缺少mybatis-generator-core.jar
https://blog.csdn.net/qq_36688143/article/details/82014889
MyBatis Generator http://www.mybatis.org/generator/index.html
MyBatis GeneratorXML Configuration File Referencehttp://www.mybatis.org/generator/configreference/xmlconfig.html
Dependency Information http://www.mybatis.org/generator/dependency-info.html
注意2
这里jdbc连接处的connectionURL为
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT" userId="root" password="12345678">
而不是
mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
主要是因为XML中&为转义符的原因
下面是五个在XML文件中预定义好的实体:
< |
< |
小于号 |
> |
> |
大于号 |
& |
& |
和 |
' |
’ |
单引号 |
" |
" |
双引号 |
实体必须以符号"&"开头,以符号";"结尾。
注意: 只有"<" 字符和"&"字符对于XML来说是严格禁止使用的。剩下的都是合法的,为了减少出错,使用实体是个好习惯。
https://blog.csdn.net/teedry/article/details/5816687
自动生成代码
点击run----> Edit Configurations
ok
从上往下我依次贴一下自动生成的代码
public interface UserMapper {
int deleteByPrimaryKey(Long id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
public class User {
private Long id;
private String name;
private Integer age;
private String email;
public Long getId() {
return id;
}
public void setId(Long 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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
}
<?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.example.mybatis_demo.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.example.mybatis_demo.po.User" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="email" property="email" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, name, age, email
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
select
<include refid="Base_Column_List" />
from user_info
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
delete from user_info
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.example.mybatis_demo.po.User" >
insert into user_info (id, name, age,
email)
values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{email,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.example.mybatis_demo.po.User" >
insert into user_info
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="age != null" >
age,
</if>
<if test="email != null" >
email,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=BIGINT},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
<if test="email != null" >
#{email,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.example.mybatis_demo.po.User" >
update user_info
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
<if test="email != null" >
email = #{email,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.mybatis_demo.po.User" >
update user_info
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
email = #{email,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
5. SpringBoot启动类加注解@MapperScan
@SpringBootApplication
@MapperScan("com.example.mybatis_demo.mapper")
public class MybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisDemoApplication.class, args);
}
}
6 测试
就测试一下删除
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisDemoApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void contextLoads() {
}
@Test
public void testDelete(){
int i = userMapper.deleteByPrimaryKey((long) 1);
System.out.println(i);
assert(i==1);
}
}
id为1的已经删除了
教程就到这里
主要参考
https://blog.csdn.net/guobinhui/article/details/79289189
https://blog.csdn.net/winter_chen001/article/details/77249029