您的位置:首页 > 编程语言 > Java开发

IDEA spring boot 连接Postgresql配置 【已解决】

2019-03-09 15:23 1411 查看

1.IDEA创建项目


修改 C:\Program Files\PostgreSQL\9.4\data路径下的 pg_hba.conf配置信息

# METHOD can be "trust", "reject", "md5", "password", "gss", "sspi",
# "ident", "peer", "pam", "ldap", "radius" or "cert".  Note that
# "password" sends passwords in clear text; "md5" is preferred since
# it sends encrypted passwords.

这里解释了配置信息,我们只需要将自己电脑ipv4/ipv6对应的 METHOD修改成trust就可以使用。我的电脑采用的ipv4,所以我修改的是ipv4的METHOD为trust。

2.创建application.yml文件,写入驱动接口

spring:
datasource:
url: jdbc:postgresql://172.30.105.178:5432/mysql?useSSL=false
username: postgres
password: 0000
driverClassName: org.postgresql.Driver

JpaPostgresqlApplicationTests.java

package com.qingsong.jdbc_test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class JdbcTestApplicationTests {

@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
System.out.println("连接成功");
System.out.println("dataSource.getClass()内容***"+dataSource.getClass());

Connection connection = dataSource.getConnection();
System.out.println("connection内容***"+connection);
connection.close();

}
}

controller.java

package com.qingsong.mybatis_mysql.control;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
* @Auther: 青松
* @Date: 2019/3/5 20:19
*/
@Controller
public class controller {
/**
* @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法。
* 在使用@Autowired之前,我们对一个bean配置起属性时,是这用的
*/
@Autowired
JdbcTemplate jdbcTemplate;

@ResponseBody
@GetMapping("/hi")
public Map<String,Object> map(){
List<Map<String,Object>> list=jdbcTemplate.queryForList("select  * from  author");
return list.get(0);
}
}

Author.sql

create table Author
(
code varchar(20) primary key,
name varchar(20) not null
);

application.properties

# schema.sql中一般存放的是DDL脚本

spring.datasource.schema=classpath:Author.sql
spring.datasource.initialization-mode=always

运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: