springboot整合mybatis配置详解

   2024-10-01 4530
核心提示:在Spring Boot项目中整合MyBatis需要做以下配置:1、添加MyBatis和MyBatis-Spring依赖在pom.xml文件中添加MyBatis和MyBatis-Spri

在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/testspring.datasource.username=rootspring.datasource.password=rootspring.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文件,例如:

@Mapperpublic 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中的方法执行数据库操作,例如:

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号