1.前言
本文主要介绍如何用springboot连接oracle数据库
使用技术:springboot,mybatis,maven
开发工具:intellij idea
数据库:oracle
本文只演示查询oracle数据库中的数据,增删改雷同,不一一演示.
程序完整代码:github下载
2.oracle数据库准备
注意:maven不能下载Oracle JDBC驱动,请在开始本教程前,确保已经下载好和本地oracle数据库相对应的驱动版本.
创建测试数据,表名:HERO,插入一条数据
3.步骤详解
项目结构
pom.xml
放到github上自行查看.
application.properties
记得改登陆用户名和密码
#端口
server.port=8080
#oracle数据库配置
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=zgr666
spring.datasource.password=zgr666
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
#mapper文件地址
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
网上有些教程 driver-class-name=oracle.jdbc.driver.oracleDriver,本教程是oracle.jdbc.oracleDriver, oracle9版本之后选用第二种写法.
准备Mapper文件
TestMapper.java
@Mapper
public interface TestMapper {
String getOne();
}
TestMapper.xml
<select id="getOne" resultType="String">
select SPEED from HERO where ID = 1
</select>
xml文件省略了一些内容,请加上其他外部引用.
准备Service和impl
TestService.java
public interface TestService {
String getOne();
}
TestServiceImpl.java
@Service
public class TestServiceImpl implements TestService {
@Autowired
TestMapper testMapper; //如果这里编辑器报错了,请在mapper.java中加上@Component("TestMapper")即可.
@Override
public String getOne() {
System.out.println("进来impl了!");
return testMapper.getOne();
}
}
Controller
@Controller
public class TestController {
@Autowired
private TestService testService;
@RequestMapping(value = "/test")
public void testPage(){
System.out.println("testService.getOne() = "+testService.getOne());
}
}
在Application文件中加上@MapperScan
框内路径请自行修改.
运行
观察控制台输出内容.
遇到的坑
把@Service,@Component,@Resource,@Autowired,@MapperScan等一些java和spring标签搞清楚,要不各种问题.
不习惯oracle控制台操作,就下载一个图形界面(Navicat Premium).
maven不能自动下载Oracle的JDBC驱动,自行百度下载.
刚开始写博客,若有错误请指出.
最后欢迎大家进群交流技术.
技(chui)术(shui)交流群 : 692244671