Springboot整合Mybatis和SQLite
要在Spring Boot中整合MyBatis和SQLite,你需要做以下几步:
- 添加依赖到
pom.xml
:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- SQLite JDBC Driver -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.3</version>
</dependency>
<!-- 添加测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
:
# 数据源配置
spring.datasource.url=jdbc:sqlite:path_to_your_database.db
spring.datasource.driver-class-name=org.sqlite.JDBC
# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.yourpackage.model
- 创建Mapper接口和XML文件:
package com.yourpackage.mapper;
public interface YourModelMapper {
// 定义操作数据库的方法
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yourpackage.mapper.YourModelMapper">
<!-- 定义SQL语句 -->
</mapper>
- 创建Service层和Controller层:
package com.yourpackage.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@Autowired
private YourModelMapper mapper;
// 调用mapper方法实现业务逻辑
}
package com.yourpackage.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YourController {
@Autowired
private YourService service;
// 调用service方法处理请求
}
- 创建Spring Boot启动类:
package com;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot
评论已关闭