Springmvc 访问postgreSQL数据库

381 阅读1分钟

postgreSQL下载地址

首先,pom.xml中添加依赖。

<dependency><!-- jdbc templete -->
	<groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>4.2.0.RELEASE</version>
</dependency>
<dependency><!-- dbcp -->
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-dbcp2</artifactId>
	<version>2.1.1</version>
</dependency>
<dependency><!-- postgresql -->
	<groupId>org.postgresql</groupId>
	<artifactId>postgresql</artifactId>
	<version>9.4-1206-jdbc42</version>
</dependency>

第二,root-context.xml中添加dataSource,properties文件位置,jdbcTemplate的bean。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
	
<bean id="basicDataSource" class="org.apache.commons.dbcp2.BasicDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
	<property name="maxTotal" value="${jdbc.maxTotal}" />
</bean>
<context:property-placeholder location="classpath:/jdbc.properties"/>

<bean class="org.springframework.jdbc.core.JdbcTemplate">
	<constructor-arg ref="basicDataSource" />
</bean>
	

最后,在src/main/resources/下生成jdbc.properties。

jdbc.driverClassName=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/postgres
jdbc.username=postgres
jdbc.password=postgres

生成一个controller测试能否访问数据库。

@RestController
public class TestJDBCController {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@RequestMapping(value="/jdbc")
	public List<Map<String, Object>> show() {
		List<Map<String, Object>> rets = jdbcTemplate.queryForList("select * from Staff");
		return rets;
	}
}

以下是浏览器结果。