在使用mybatis的时候,我们需要自己建立实体类、接口和对应的映射文件。一个字母写错就可能导致运行不起来,很是麻烦。使用generator可以帮助我们自动生成上述的文件。
首先,新建一个springboot项目:
选择mybatis和mysql的依赖,如下图:
点击finish,删除多余的文件,删除后的项目结构如下图:
打开pom.xml,添加generator的相关依赖
org.mybatis.generator mybatis-generator-maven-plugin 1.4.0 Generate MyBatis Artifacts generate true true ${basedir}/src/main/resources/generator/generatorConfig.xml
完整的pom.xml如下:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.3 com.example demo1 0.0.1-SNAPSHOT demo1 demo1 1.8 org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.2 mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.mybatis.generator mybatis-generator-maven-plugin 1.4.0 Generate MyBatis Artifacts generate true true ${basedir}/src/main/resources/generator/generatorConfig.xml
打开resources文件夹下的application.properties,配置mybatis:
# mapper.xml配置文件的路径 MyBatis.mapper-locations=classpath:/mapper/*.xml #MyBatis.type-aliases-package=com.example.springBootMybatisProject.entity # 数据库配置 spring.datasource.url=jdbc:mysql://localhost:3306/MyBatis_test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true spring.datasource.username=root spring.datasource.password=123123 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
建立MyBatis_test数据库和student表,代码如下:
create database MyBatis_test;
CREATE TABLE student( sno VARCHAR(20) PRIMARY KEY, sname varchar(20), sex varchar(20), birthday VARCHAR(20), phone varchar(20), dorm VARCHAR(20) );
在resources文件夹下建立generator文件夹,然后建立generatorConfig.xml文件,如下图:
在generatorConfig.xml中添加如下代码:
注意:
其中的数据库驱动位置更改为你本地磁盘的数据库驱动位置,上面的路径是我自己的。
数据库的用户名和密码改为你自己的
点击idea右边的Maven:
双击运行插件:
发现项目中已经添加了实体类,接口,映射文件
在启动类中添加对Mapper包的扫描注解@MapperScan,Spring Boot启动时会自动加载包路径下的Mapper。
打开测试类,测试代码如下:
package com.example.demo;
import com.example.demo.entity.Student;
import com.example.demo.mapper.StudentMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Demo1ApplicationTests {
@Autowired
private StudentMapper studentMapper;
@Test
void contextLoads() {
Student student1=new Student("1001","浮生","男","2001-1-1","231241414","123");
Student student2=new Student("1002","张三","女","2002-2-2","222121212","123");
Student student3=new Student("1001","123","女","123","123","123");
Student student4=new Student("1003","333","女","333","333","333");
System.out.println("添加学生成功!");
studentMapper.insert(student1);
studentMapper.insert(student2);
System.out.println("删除学生成功!");
studentMapper.deleteByPrimaryKey("1002");
System.out.println("修改学生成功!");
studentMapper.updateByPrimaryKey(student3);
System.out.println("学生信息如下:");
System.out.println(studentMapper.selectByPrimaryKey("1001"));
System.out.println("全部学生信息如下:");
studentMapper.insert(student4);
System.out.println(studentMapper.selectAll());
}
}
运行结果如下:
数据库信息:



