springboot+mybaits
时间: 2023-10-06 12:09:41 浏览: 40
Spring Boot 和 MyBatis 是两个非常流行的开源框架,可以用于构建高效、可靠的 Java Web 应用程序。Spring Boot 提供了一种简单的方式来创建独立的、基于 Spring 的应用程序,而 MyBatis 是一个基于 Java 的持久层框架,它可以帮助开发人员更快地开发数据库相关的应用程序。
结合使用 Spring Boot 和 MyBatis 可以实现快速、高效的开发。在使用 Spring Boot 和 MyBatis 的过程中,我们可以使用 Spring Boot 的自动配置和依赖管理功能,使得整个应用程序的配置和管理变得更加简单。同时,MyBatis 提供了一种简单的方式来访问数据库,也可以使用 MyBatis 提供的一些高级功能,如缓存、分页等。
在使用 Spring Boot 和 MyBatis 开发应用程序时,我们需要添加相应的依赖,并进行配置,具体步骤如下:
1. 添加 Spring Boot 和 MyBatis 的依赖:在 pom.xml 文件中添加以下依赖:
```xml
<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>2.2.0</version>
</dependency>
```
2. 添加数据库配置:在 application.properties 文件中配置数据库相关参数,如下所示:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
```
3. 添加 MyBatis 的映射文件和实体类:在 resources 目录下创建 mapper 和 entity 目录,然后在 mapper 目录下创建与实体类对应的 XML 文件,如下所示:
```xml
<?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.demo.mapper.UserMapper">
<select id="getUserById" parameterType="int" resultType="com.example.demo.entity.User">
select * from user where id = #{id}
</select>
</mapper>
```
在 entity 目录下创建实体类,如下所示:
```java
public class User {
private int id;
private String name;
private String password;
// 省略 getter 和 setter 方法
}
```
4. 添加 MyBatis 的 Mapper 类:在 com.example.demo.mapper 目录下创建 UserMapper 接口,如下所示:
```java
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User getUserById(int id);
}
```
5. 添加 Service 层和 Controller 层:在 com.example.demo.controller 目录下创建 UserController 类,如下所示:
```java
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id") int id) {
return userMapper.getUserById(id);
}
}
```
6. 运行程序:使用 Maven 运行项目,然后在浏览器中输入 http://localhost:8080/user/{id},其中 {id} 为实际的用户 ID,即可查看该用户的信息。
通过以上步骤,我们就可以使用 Spring Boot 和 MyBatis 快速构建一个基于 Web 的应用程序。