数据库创建
CREATE SCHEMA test
DEFAULT CHARACTER SET utf8 ;
CREATE TABLE t1
(
id
int NOT NULL AUTO_INCREMENT,
name
varchar(45) DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
创建项目
打开IntelliJ IDEA 2021
安装MyBatis插件
装上Properties To Yaml Converter插件并转换application.properties为application.yml
用Mybatis Generator生成模型和DAO
修改pom.xml,在<build><;plugins>里加入插件描述:
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
</plugin>
在pom.xml鼠标右键,选择Maven-Reload Project,刷新Manven库:
在src/main/resources新建mybatis 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>
<!—这里驱动的路径改为自己的,以下targetProject都要改成自己的路径->
<classPathEntry location=“C:/Users/wiseyao/.m2/repository/mysql/mysql-connector-java/8.0.25/mysql-connector-java-8.0.25.jar”/>
<context id=“productRelease”>
<property name=“mergeable” value=“false” />
<plugin type=“org.mybatis.generator.plugins.SerializablePlugin” />
<jdbcConnection driverClass=“com.mysql.jdbc.Driver”
connectionURL=“jdbc:mysql://localhost:3306/test”
userId=“root” password=“123456” />
<javaModelGenerator targetPackage=“com.example.demo.model”
targetProject=“D:/WiseSoft/project/2021/BaJinSi/BaoGuan/03code/demo/src/main/java” />
<sqlMapGenerator targetPackage=“mapper”
targetProject=“D:/WiseSoft/project/2021/BaJinSi/BaoGuan/03code/demo/src/main/resources” />
<javaClientGenerator targetPackage=“com.example.demo.dao”
targetProject=“D:/WiseSoft/project/2021/BaJinSi/BaoGuan/03code/demo/src/main/java” type=“XMLMAPPER” />
<table tableName=“t1” enableCountByExample=“true” enableDeleteByExample=“true” enableDeleteByPrimaryKey=“true” enableInsert=“true” enableSelectByExample=“true” enableSelectByPrimaryKey=“true” enableUpdateByExample=“true” enableUpdateByPrimaryKey=“true”/>
</context>
</generatorConfiguration>
运行Mybatis Generator:
修改启动类DemoApplication
@SpringBootApplication
@MapperScan(“com.example.demo.dao”)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
加上了:@MapperScan(“com.example.demo.dao”)
测试类
路径:com.example.demo.controller.TestController,内容:
@RestController
public class TestController {
@Autowired
private T1Mapper t1Mapper;
@GetMapping("testDao")
public List<T1> testDao(){
List<T1> list=t1Mapper.selectByExample(null);
return list;
}
}