在Spring Boot項目中整合MyBatis需要做以下配置:
1、添加MyBatis和MyBatis-Spring依賴
在pom.xml文件中添加MyBatis和MyBatis-Spring的依賴:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
2、配置數據源
在application.properties文件中配置數據源相關信息,例如:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3、配置MyBatis
創建一個MyBatis的配置類,配置MapperScannerConfigurer和SqlSessionFactoryBean:
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return sqlSessionFactoryBean.getObject();
}
}
4、創建Mapper接口和對應的XML文件
創建Mapper接口和對應的XML文件,例如:
@Mapper
public interface UserMapper {
User selectUserById(Long id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(Long id);
}
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUserById" resultType="User">
select * from user where id = #{id}
</select>
<insert id="insertUser">
insert into user (id, name, age) values (#{id}, #{name}, #{age})
</insert>
<update id="updateUser">
update user set name = #{name}, age = #{age} where id = #{id}
</update>
<delete id="deleteUser">
delete from user where id = #{id}
</delete>
</mapper>
5、在Service中使用Mapper
在Service中注入Mapper,并調用Mapper中的方法執行數據庫操作,例如:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.selectUserById(id);
}
@Transactional
public void saveUser(User user) {
userMapper.insertUser(user);
}
@Transactional
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Transactional
public void deleteUser(Long id) {
userMapper.deleteUser(id);
}
}
通過以上步驟,就可以在Spring Boot項目中成功整合MyBatis,并使用MyBatis進行數據庫操作。