91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

springboot整合mybatis配置詳解

小億
83
2024-08-26 14:30:15
欄目: 編程語言

在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進行數據庫操作。

0
隆尧县| 通辽市| 屯门区| 彭泽县| 岳阳市| 繁峙县| 申扎县| 镇远县| 浦城县| 临夏县| 鹤峰县| 盈江县| 舒兰市| 开平市| 耿马| 横峰县| 拉孜县| 华阴市| 平昌县| 济南市| 什邡市| 天峻县| 安平县| 上虞市| 洪泽县| 湖州市| 秦皇岛市| 长子县| 景宁| 彭阳县| 渝中区| 维西| 宁南县| 长沙县| 西藏| 敦煌市| 南部县| 巴东县| 涞源县| 枝江市| 泾阳县|