欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot 整合 MyBatis 连接 Oracle数据库

程序员文章站 2022-05-19 12:41:41
1、Spring Boot项目添加MyBatis依赖和Oracle驱动: 2、配置application.properties: 3、新建实体类,注意与数据库字段对应: 4、新建mapper(xml): 5、新建dao接口: 此处应加@Mapper注解,interface的方法名对应xml的标签id ......

1、Spring Boot项目添加MyBatis依赖和Oracle驱动:

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.2</version>
</dependency>
<dependency>
	<groupId>com.oracle</groupId>
	<artifactId>ojdbc6</artifactId>
	<version>11.2.0.1.0</version>
</dependency>

2、配置application.properties:

#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/ems
#spring.datasource.username=root
#spring.datasource.password=root
mybatis.mapper-locations=classpath:/com/example/demo/mapper/*.xml
server.port=9090
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@134.32.9.247:1700/mbss
spring.datasource.username=dbrtadm
spring.datasource.password=dbrtadm

3、新建实体类,注意与数据库字段对应:

package com.example.demo.entity;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class User {
	public int id;
	public String order_id;
}

4、新建mapper(xml):

<?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.example.demo.dao.UserMapper">  
    <select id = "listUser" resultType="com.example.demo.entity.User">
        select * from t_ps_order_qr
    </select>
</mapper>

5、新建dao接口:

package com.example.demo.dao;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
	public List listUser();
}

 此处应加@Mapper注解,interface的方法名对应xml的标签id。

6、新建controller:

package com.example.demo.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.UserMapper;

@RestController
public class TestController {
	@Resource
	UserMapper um;
	
	@GetMapping("/listu")
	public List listUser() {
		return um.listUser();
	}
}

 启动主程序,浏览器访问http://localhost:9090/listu,

Spring Boot 整合 MyBatis 连接 Oracle数据库


 

注意oracle驱动版本问题,版本不对可能会报错Spring Boot 整合 MyBatis 连接 Oracle数据库

需要连接MySQL只需将驱动和URL更改为MySQL的即可,其余与Oracle相同。

如有错误欢迎指正。