在Spring Boot项目中整合MyBatis需要做以下配置:
1、添加MyBatis和MyBatis-Spring依赖
在pom.xml文件中添加MyBatis和MyBatis-Spring的依赖:
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
${mybatis.spring.version}
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);
}
insert into user (id, name, age) values (#{id}, #{name}, #{age})
update user set name = #{name}, age = #{age} where id = #{id}
delete from user where id = #{id}
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进行数据库操作。