黑马springboot中整合mybatis中的删除
时间: 2023-11-12 13:09:05 浏览: 86
SpringBoot整合mybatis
1. 首先,在pom.xml文件中添加mybatis和mysql依赖:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
2. 在application.properties文件中配置数据库信息:
```
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
```
3. 创建一个测试实体类:
```
public class User {
private Long id;
private String username;
private String password;
// 省略getter和setter方法
}
```
4. 创建一个UserMapper接口:
```
@Mapper
public interface UserMapper {
int insert(User user);
int update(User user);
int delete(Long id);
User selectById(Long id);
List<User> selectAll();
}
```
5. 创建一个UserMapper.xml文件,定义相关SQL语句:
```
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
</resultMap>
<select id="selectById" resultMap="BaseResultMap">
select * from user where id = #{id}
</select>
<select id="selectAll" resultMap="BaseResultMap">
select * from user
</select>
<insert id="insert" parameterType="com.example.demo.entity.User">
insert into user (username, password)
values (#{username}, #{password})
</insert>
<update id="update" parameterType="com.example.demo.entity.User">
update user
set username = #{username},
password = #{password}
where id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Long">
delete from user
where id = #{id}
</delete>
</mapper>
```
6. 在UserService中注入UserMapper:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public int insert(User user) {
return userMapper.insert(user);
}
public int update(User user) {
return userMapper.update(user);
}
public int delete(Long id) {
return userMapper.delete(id);
}
public User selectById(Long id) {
return userMapper.selectById(id);
}
public List<User> selectAll() {
return userMapper.selectAll();
}
}
```
7. 在Controller中调用UserService中的delete方法:
```
@RestController
public class UserController {
@Autowired
private UserService userService;
@DeleteMapping("/users/{id}")
public String deleteUser(@PathVariable("id") Long id) {
int result = userService.delete(id);
if (result > 0) {
return "删除成功";
} else {
return "删除失败";
}
}
}
```
这样就完成了使用mybatis在springboot中整合mysql的删除操作。
阅读全文