Spring Boot + Mybatis

需求:
持久化框架 Mybatis 整合到 web 项目。

添加依赖:

<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <!-- MyBatis Spring Boot Starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>3.0.0</version> <!-- 使用适合你的项目的版本 -->
    </dependency>
 	
 	<!-- 数据库驱动 -->
</dependencies>

配置数据源:

spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath*:mapper/*.xml
mybatis.config-location=classpath:mybatis-config.xml

创建 Mapper 接口:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM users")
    List<User> findAll();
}

创建 XML Mapper(可选)

使用 XML 文件定义 SQL,可以在 src/main/resources/mapper 目录下创建 XML 文件,例如 UserMapper.xml:

<mapper namespace="com.example.mapper.UserMapper">
  <select id="findAll" resultType="com.example.model.User">
    SELECT * FROM users
  </select>
</mapper>

IDEA小技巧,可以快捷设置文件模版,方便快捷键创建 xml 文件:
在这里插入图片描述

maven打包配置:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
</build>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值