写一个简单的springboot集合mybatis的代码
时间: 2024-06-11 22:08:45 浏览: 134
java毕业设计 基于SpringBoot+Mybatis的学生宿舍管理系统的设计与实现+详细文档+全部资料(优秀项目).zip
这里提供一个简单的Spring Boot集成MyBatis的示例代码:
1. 首先在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.1.4</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>runtime</scope>
</dependency>
```
2. 创建一个实体类User.java:
```java
public class User {
private Long id;
private String name;
private Integer age;
// 省略getter和setter方法
}
```
3. 创建一个Mapper接口UserMapper.java:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO users(name, age) VALUES(#{name}, #{age})")
void save(User user);
@Update("UPDATE users SET name=#{name}, age=#{age} WHERE id=#{id}")
void update(User user);
@Delete("DELETE FROM users WHERE id=#{id}")
void delete(Long id);
}
```
4. 创建一个MyBatis配置文件application.yml:
```yaml
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity
```
5. 在resources目录下创建一个mapper目录,然后在mapper目录下创建一个UserMapper.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">
<resultMap id="userMap" type="com.example.demo.entity.User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
</resultMap>
<select id="findById" resultMap="userMap">
SELECT * FROM users WHERE id=#{id}
</select>
<insert id="save" parameterType="com.example.demo.entity.User">
INSERT INTO users(name, age) VALUES(#{name}, #{age})
</insert>
<update id="update" parameterType="com.example.demo.entity.User">
UPDATE users SET name=#{name}, age=#{age} WHERE id=#{id}
</update>
<delete id="delete" parameterType="Long">
DELETE FROM users WHERE id=#{id}
</delete>
</mapper>
```
6. 创建一个Controller类UserController.java:
```java
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userMapper.findById(id);
}
@PostMapping("/users")
public String saveUser(@RequestBody User user) {
userMapper.save(user);
return "success";
}
@PutMapping("/users")
public String updateUser(@RequestBody User user) {
userMapper.update(user);
return "success";
}
@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable Long id) {
userMapper.delete(id);
return "success";
}
}
```
7. 运行Spring Boot应用,访问http://localhost:8080/users/{id}可以获取指定id的用户信息,访问http://localhost:8080/users可以新增用户,访问http://localhost:8080/users可以更新用户信息,访问http://localhost:8080/users/{id}可以删除指定id的用户。
阅读全文