pg数据库 springboot

springboot怎么连接pg数据库

小亿
495
2024-05-14 10:44:26
栏目: 大数据

要连接PostgreSQL数据库,首先需要在Spring Boot项目中添加相应的依赖。在`pom.xml`文件中添加如下依赖:

```xml

org.springframework.boot

spring-boot-starter-data-jpa

org.postgresql

postgresql

```

然后在`application.properties`文件中配置数据库连接信息:

```properties

spring.datasource.url=jdbc:postgresql://localhost:5432/database_name

spring.datasource.username=username

spring.datasource.password=password

spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

spring.jpa.hibernate.ddl-auto=update

```

在以上配置中,需要修改`database_name`、`username`、`password`为你的数据库的名称、用户名和密码。

最后,在你的Spring Boot应用程序中,你可以使用`@Autowired`注解注入`JdbcTemplate`或`EntityManager`来进行数据库操作。例如:

```java

@Autowired

JdbcTemplate jdbcTemplate;

public void queryData() {

List> results = jdbcTemplate.queryForList("SELECT * FROM table_name");

// 处理查询结果

}

@Autowired

EntityManager entityManager;

public void saveData() {

// 使用JPA实体类进行数据操作

}

```

通过以上步骤,你就可以在Spring Boot应用程序中连接并操作PostgreSQL数据库了。

0
看了该问题的人还看了