这里写自定义目录标题
springboot集成mybatis-plus
搭建一个springboot项目
点击next
把java版本改成8,点击next
选择springboot版本2.4.2 点击next
选择项目地址点击finish
在pom文件里加入依赖
<dependencies>
<!--spring整合mvc的-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热部署的包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--lombok包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--测试类的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--导入JDBC-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--导入数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--添加mybatisplus包-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
创建application.yml文件添加数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/dbtest?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
username: root
password: root
测试数据源链接是否成功
编写实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
创建mapper文件继承BaseMapper
开始测试(记得在启动类上加@MapperScan(“mapper的全路径名”)) 不然会报错找不到映射文件
@SpringBootTest
class DemoApplicationTests {
@Autowired
private DataSource dataSource;
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() throws SQLException {
System.out.println("获取的数据库连接为:"+dataSource.getConnection());
}
@Test
void insertTest(){
User user = new User();
user.setId(8L);
user.setAge(18);
user.setEmail("110@qq.com");
user.setName("冷暖");
userMapper.insert(user);
}
}
数据库插入成功