Spring Boot Integrates MyBatis to Connect to Oracle Database

Keywords: Java Spring Mybatis Oracle MySQL

1. Spring Boot project adds MyBatis dependencies and Oracle drivers:

<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. Configure 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. Create a new entity class and note that it corresponds to a database field:

package com.example.demo.entity;

import lombok.Getter;
import lombok.Setter;

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

4. New 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. New dao interface:

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

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

The @Mapper comment should be added here, and the method name of the interface corresponds to the label id of the xml.

6. New 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();
	}
}

Start the main program, browser access http://localhost:9090/listu,

 

Note oracle driver version issues, incorrect version may cause errors.

To connect to MySQL, simply change the driver and URL to MySQL, and the rest are the same as Oracle.

If there are any errors, please correct them.

Posted by mtimdog on Sat, 25 Jan 2020 08:22:24 -0800