让Spring Web服务连接Oracle数据库

依然是Spring官网。

http://spring.io/guides/gs/relational-data-access/

介绍了Spring框架如何通过JDBC连接数据库(H2数据库-一种嵌入式数据库,类似Android平台下SQLite),可是通篇没有介绍如何建立数据库连接。

而我的目标是连接Oracle数据库,怎么办呢?受到Spring的启发,最后拼凑代码终于连接上Oracle数据库。

下面,同样采用Gradle工具管理项目。项目文件build.gradle内容如下:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.6.RELEASE")
        classpath files("lib/ojdbc6.jar")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-relational-data-access'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework:spring-jdbc")
    compile("com.h2database:h2")
    compile files("lib/ojdbc6.jar")
    testCompile("junit:junit")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}
在项目依赖中增加本地jar包"ojdbc6.jar"-Oracle提供JDBC实现包。

创建一个表对应实体类(Oracle 11g scott/tiger 示例DEPT表)

src/main/java/hello/Department.java

package hello;

public class Department {

	private long id;
	private String name, loc;

	public Department(long id, String name, String loc) {
		this.id = id;
		this.name = name;
		this.loc = loc;
	}

	public String toString() {
		return String.format("Department[id=%d, name='%s', loc='%s']", id, name, loc);
	}

	public long getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String getLoc() {
		return loc;
	}
}
创建一个JDBCHelper类

src/main/java/hello/JdbcHelper.java

package hello;

import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

public class JdbcHelper {

	private static JdbcTemplate jdbcTemplate = new JdbcTemplate();
	
	static {
		SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
		dataSource.setDriverClass(oracle.jdbc.driver.OracleDriver.class);
		dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
		dataSource.setUsername("scott");
		dataSource.setPassword("tiger");
		
		jdbcTemplate.setDataSource(dataSource);
	}
	
	public static Department getDeptById(long id) {
		List<Department> list = new ArrayList<Department>();
		
		jdbcTemplate.query("SELECT * FROM DEPT WHERE DEPTNO = ?", new Object[] {id}, 
				(rs, rowNum) -> new Department(rs.getLong("DEPTNO"), rs.getString("DNAME"), rs.getString("LOC"))	
				).forEach(department -> list.add(department));
		
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		
		return null;
	}
	
	public static List<Department> getDeptByName(String name) {
		List<Department> list = new ArrayList<Department>();
		
		jdbcTemplate.query("SELECT * FROM DEPT WHERE DNAME = ?", new Object[] {name}, 
				(rs, rowNum) -> new Department(rs.getLong("DEPTNO"), rs.getString("DNAME"), rs.getString("LOC"))	
				).forEach(department -> list.add(department));
		
		return list;
	}
}
核心是org.springframework.jdbc.core.JdbcTemplate类。直接使用SQL语句操作数据库。

当然,还需要将数据库操作结果通过Web服务发布出去。

创建一个REST服务发布类。

src/main/java/hello/GreetingController.java

package hello;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
		System.out.println("greeting service called.");
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
    
    @RequestMapping("/getDepartById")
    public Department getDepartById(@RequestParam(value="id", defaultValue="10") String id) {
    	return JdbcHelper.getDeptById(new Long(id));
    }
    
    @RequestMapping("/getDeptByName")
    public List<Department> getDeptByName(@RequestParam(value="name", defaultValue="市场部") String name) {
    	return JdbcHelper.getDeptByName(name);
    }
    
}
/getDapartById

通过Id查询Department实体对应数据库中DEPT表记录,id作为参数,默认值为10。通过JdbcHelper类中getDeptById方法得到JSON格式数据。譬如:

http://localhost:8080/getDepartById

返回结果:

{"id":10,"name":"ACCOUNTING","loc":"NEW YORK"}

/getDeptByName

通过“name”字段查询Oracle中DEPT表记录,name作为参数,默认值为“市场部”。

http://localhost:8080/getDeptByName

返回结果:

[{"id":50,"name":"市场部","loc":"中国上海"},{"id":60,"name":"市场部","loc":"Alagas"},{"id":80,"name":"市场部","loc":"巴黎"}]

URL可以传入参数,譬如:

http://localhost:8080/getDeptByName?name=销售部

返回结果:

[{"id":45,"name":"销售部","loc":"越南"},{"id":46,"name":"销售部","loc":"越南"},{"id":42,"name":"销售部","loc":"埃及开罗"},{"id":47,"name":"销售部","loc":"越南"},{"id":44,"name":"销售部","loc":"越南"}]

Spring通过Jackson JSON库自动将字符转换为JSON格式文本或者JSON数组格式。

其实,可以将JdbcHelper类直接作为Web服务发布出去。建立数据库连接后,即可将数据库操作结果通过文本方式发布出去。

你可能感兴趣的:(oracle,jdbc,spring-data,spring-web)