springboot整合mybatis配置详解

avatar
作者
筋斗云
阅读量:0

在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进行数据库操作。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!