在spring boot中结合mybatis执行一个脚本去MySQL数据库插入数据
时间: 2023-11-25 18:04:18 浏览: 101
首先,在pom.xml文件中添加MyBatis和MySQL连接驱动的依赖:
```xml
<dependencies>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
```
然后,在application.properties文件中添加MySQL数据库的连接配置:
```
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
接下来,创建一个Mapper来执行插入数据的SQL脚本。比如,创建一个UserMapper,添加插入用户数据的方法:
```java
@Mapper
public interface UserMapper {
@Insert("INSERT INTO user (name, age) VALUES (#{name}, #{age})")
int insertUser(@Param("name") String name, @Param("age") int age);
}
```
最后,在Spring Boot应用程序中注入UserMapper,调用insertUser方法插入数据:
```java
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private UserMapper userMapper;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
userMapper.insertUser("Tom", 25);
userMapper.insertUser("Jerry", 20);
}
}
```
以上就是在Spring Boot中结合MyBatis执行一个脚本去MySQL数据库插入数据的步骤。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)