spring整合mybatis对数据库实现增删改
时间: 2023-08-12 11:23:55 浏览: 54
好的,这个问题我可以回答。首先需要在项目的pom.xml文件中添加mybatis和mybatis-spring的依赖。
```
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
```
接着,在Spring配置文件中配置数据源和SqlSessionFactory,这里以MySQL数据库为例:
```
<!-- 数据源配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- SqlSessionFactory配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- MapperScannerConfigurer配置 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
```
在上面的配置中,我们指定了数据源的类型和连接信息,然后配置了SqlSessionFactory,同时指定了mybatis的配置文件位置。最后,我们配置了MapperScannerConfigurer,指定了Mapper接口所在的包。
接下来,我们就可以编写Mapper接口和对应的SQL语句了。例如,我们有一个User表,需要实现对该表的增删改查操作,那么我们可以先定义一个UserMapper接口:
```
public interface UserMapper {
void insert(User user);
void deleteById(int id);
void update(User user);
User findById(int id);
}
```
这里定义了四个方法,分别对应了插入、删除、更新和查询操作。接着,我们需要在mybatis的配置文件中定义这些SQL语句:
```
<mapper namespace="com.example.mapper.UserMapper">
<insert id="insert" parameterType="com.example.entity.User">
insert into user (name, age) values (#{name}, #{age})
</insert>
<delete id="deleteById" parameterType="int">
delete from user where id = #{id}
</delete>
<update id="update" parameterType="com.example.entity.User">
update user set name = #{name}, age = #{age} where id = #{id}
</update>
<select id="findById" parameterType="int" resultType="com.example.entity.User">
select * from user where id = #{id}
</select>
</mapper>
```
在上面的配置中,我们定义了四个SQL语句,分别对应了插入、删除、更新和查询操作。其中,#{name}、#{age}和#{id}都是参数占位符,通过调用Mapper接口的方法,可以将实际参数传递给SQL语句进行执行。
最后,我们就可以在Service层中调用Mapper接口的方法,来完成对数据库的增删改查操作了。例如,我们有一个UserService类,需要实现对User表的增删改查操作,那么我们可以这样定义该类:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public void insert(User user) {
userMapper.insert(user);
}
public void deleteById(int id) {
userMapper.deleteById(id);
}
public void update(User user) {
userMapper.update(user);
}
public User findById(int id) {
return userMapper.findById(id);
}
}
```
在上面的代码中,我们使用了@Autowired注解,将UserMapper接口注入到UserService中。然后,我们实现了UserService类的四个方法,分别对应了User表的增删改查操作。在每个方法中,我们调用了UserMapper接口的方法,来完成实际的数据库操作。
这样,我们就完成了Spring整合Mybatis,实现对数据库的增删改查操作。