从零开始:Spring Boot+Mybatis高效集成H2数据库教程
warning:
这篇文章距离上次修改已过183天,其中的内容可能已经有所变动。
// 导入Spring Boot相关依赖
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// 使用MyBatis
import org.mybatis.spring.annotation.MapperScan;
// 使用H2数据库
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
// 指定MyBatis映射器接口所在的包
@MapperScan(basePackages = "com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
// 启动Spring Boot应用
SpringApplication.run(DemoApplication.class, args);
}
}
// 在application.properties或application.yml中配置H2数据库
# 使用内存模式,不需要数据文件
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
// 创建一个Mapper接口
package com.example.demo.mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Repository
public interface ExampleMapper {
@Select("SELECT * FROM information")
String getInformation();
}
// 创建一个Service类
package com.example.demo.service;
import com.example.demo.mapper.ExampleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExampleService {
private final ExampleMapper mapper;
@Autowired
public ExampleService(ExampleMapper mapper) {
this.mapper = mapper;
}
public String getInformation() {
return mapper.getInformation();
}
}
// 创建一个Controller类
package com.example.demo.controller;
import com.example.demo.service.ExampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ExampleController {
private final ExampleService service;
@Autowired
public ExampleController(ExampleService service) {
this.service = service;
}
@GetMapping("/info")
public String getInfo() {
return service.getInformation();
}
}
在这个代码实例中,我们创建了一个简单的Spring Boot应用,整合了MyBatis和H2数据库。我们定义了一个Mapper接口来执行SQL查询,并在Service和Controller类中使用它们。同时,我们展示了如何通过注
评论已关闭