You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Heroku部署后Spring JPA Repository返回空列表问题求助

Vaadin+Spring JPA部署Heroku后REST API返回空列表排查方案

问题背景

Vaadin网站部署到Heroku后页面功能正常,但/api/roles接口始终返回空列表,本地运行完全正常,Heroku控制台无报错信息。


1. 确认Heroku数据库是否存在数据

本地逻辑正常,首先排除数据库无数据的可能:

  • 使用Heroku CLI连接数据库:
    heroku pg:psql -a axium-centrality
    
  • 执行查询验证数据:
    SELECT * FROM roles;
    

若结果为空,需同步本地数据到Heroku,可通过数据库迁移工具(Flyway/Liquibase)初始化,或手动插入测试数据。

2. 检查数据库连接配置

Spring Boot会自动读取Heroku的DATABASE_URL环境变量,但需确认配置未被本地配置覆盖:

  • 查看Heroku环境变量:
    heroku config -a axium-centrality
    
    确认DATABASE_URL存在且有效。
  • 检查application.properties/application.yml,确保没有硬编码的本地数据库配置(如H2/MySQL)覆盖生产环境配置。

3. 验证JPA实体与数据库表映射

PostgreSQL默认区分大小写,需确认实体与表结构匹配:

  • 在Heroku psql中执行\dt,确认roles表存在。
  • 检查表字段与实体类字段是否完全一致(如prefix_color、multiple_prefix等字段名、数据类型是否对应)。

4. 开启详细SQL日志排查查询逻辑

添加日志配置,查看JPA实际执行的SQL:
在application.properties中添加:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

重新部署后,通过heroku logs -a axium-centrality --tail查看实时日志,确认SQL查询语句是否正确、返回结果是否为空。

5. 排查事务与懒加载问题

虽然懒加载不影响roles表本身的查询,但可尝试为Repository方法添加事务注解,确保查询在事务上下文执行:

public interface RoleRepository extends JpaRepository<Role, Integer> {
    @Transactional
    Role findByName(String name);
}

6. 确认Spring Security配置无拦截

当前配置中web.ignoring().antMatchers("/api/**")已忽略API拦截,可临时注释安全配置测试API,排除隐藏拦截逻辑的可能。


代码优化建议

  • 减少重复数据库查询:
    @RequestMapping("")
    public List<Role> infos(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "id", required = false) Integer id) {
        System.out.println("name: " + name);
    
        if (name != null) {
            Role role = roleRepository.findByName(name);
            if (role != null) {
                System.out.println("role found");
                return List.of(role);
            }
        } else if (id != null) {
            Optional<Role> roleOpt = roleRepository.findById(id);
            if (roleOpt.isPresent()) {
                System.out.println("role found");
                return List.of(roleOpt.get());
            }
        }
        System.out.println("returning all roles");
        return roleRepository.findAll();
    }
    
  • 替换不安全的密码编码器:
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    

内容的提问来源于stack exchange,提问作者Xibalba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 04:06:25