需求:
持久化框架 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>