首页 > 解决方案 > 能够通过休眠连接到postgres,但无法通过执行查询来获取数据

问题描述

我有一个运行 postgres 数据库的 docker 容器。该容器还创建了一个 db、table 和一些测试数据。我还有一个能够连接到数据库的 spring boot hibernate 应用程序。但是,我无法执行任何查询并获取任何数据。

我已经测试通过将我的 application.properties 文件中的值更改为不存在的数据库名称来查看我连接到正确的数据库 - 当我恢复到正确的数据库名称时,java 应用程序可以工作。

我还在spring.jpa.show-sql = true我的 application.properties 文件中提供,这会打印出 sql 命令。当我在 postgres 上手动运行它时,它会返回数据。

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
@RestController
public class HelloController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/hi/{id}")
    public String hi(@PathVariable("id") int index) {
        return "Hi " + accountService.get(index).getName();
    }

    @RequestMapping("/all")
    public List<String> hey() {
        List<String> everyOne = new ArrayList<>();
        for (Account account : accountService.list()) {
            everyOne.add(account.getName());
        }
        return everyOne;
    }
}
@Service
public class AccountService {

    @Autowired
    private AccountRepository accountRepository;

    public List<Account> list() {
       return accountRepository.findAll();
    }

    public Account get(int index) {
        return accountRepository.getOne(index);
    }

}
@Repository
public interface AccountRepository extends JpaRepository<Account, Integer> {

}
@Entity
public class Account {

    @Id
    private int id;
    private String name;

    public Account() { }

    public Account(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}
spring.datasource.url=jdbc:postgresql://localhost:5432/db
spring.datasource.username= postgres
spring.datasource.password=
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation = true
spring.jpa.show-sql = true

在应用程序运行时,如果我 curl http://localhost:8080/all,我会希望返回 Account 表中的所有数据。

当我 curl http://localhost:8080/hi/2时,我收到一条错误消息说

'avax.persistence.EntityNotFoundException: 找不到 com.something.models.Account id 为 2'

由于我能够通过 hibernate 连接到数据库并在手动运行 hibernate 在 psql 命令行上生成的 sql 命令时获取数据,所以我确信我在这里遗漏了一些简单的东西。在这里的任何帮助将不胜感激。

标签: javapostgresqlhibernatedocker

解决方案


我已经弄清楚了它不起作用的原因。我的应用程序以及运行 postgres 的 docker 容器也运行良好。问题是帐户表不在 postgres 中。

出现这种情况的原因是表和插入语句没有在我在 postgres 中创建的数据库上运行,而是在默认数据库(postgres)上创建表。我意识到,当我在 docker-compose.yml 文件中被 sql 脚本分解时,对于每个 .sql 文件,它们在连接到“postgres”数据库时正在运行。通过在我的每个脚本中添加一个 '\c db',这解决了我的所有问题。


推荐阅读