mybatis整合spring增删改查的代码
时间: 2023-09-24 22:11:03 浏览: 54
好的,以下是 MyBatis 整合 Spring 的增删改查代码:
首先需要在 Spring 配置文件中配置 MyBatis 的 SqlSessionFactory 和 MapperScannerConfigurer:
```
<!-- 配置 SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.example.entity"/>
</bean>
<!-- 配置 MapperScannerConfigurer -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
```
然后定义 DAO 接口,使用 MyBatis 的注解来映射 SQL 语句:
```
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
public User getUserById(int id);
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
public int addUser(User user);
@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
public int updateUser(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
public int deleteUser(int id);
}
```
最后在 Service 类中注入 Mapper,并调用方法:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.getUserById(id);
}
public int addUser(User user) {
return userMapper.addUser(user);
}
public int updateUser(User user) {
return userMapper.updateUser(user);
}
public int deleteUser(int id) {
return userMapper.deleteUser(id);
}
}
```
以上就是 MyBatis 整合 Spring 的增删改查代码。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)