【问题标题】:JpaRepository findAll() returns empty resultJpaRepository findAll() 返回空结果
【发布时间】:2017-08-25 10:39:24
【问题描述】:

JpaRepository findAll() 方法返回空结果。我正在尝试通过使用 Spring-boot、h2 数据库和 jpa 来实现休息服务。

这是我的schema.sql

CREATE TABLE IF NOT EXISTS `City` (
  `city_id` bigint(20) NOT NULL auto_increment,
  `city_name` varchar(200) NOT NULL,
PRIMARY KEY (`city_id`));

我的data.sql 文件包括:

INSERT INTO City (city_id,city_name) VALUES(1,'EDE');
INSERT INTO City (city_id,city_name) VALUES(2,'DRUTEN');
INSERT INTO City (city_id,city_name) VALUES(3,'DELFT');

City 实体:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "City")
public class City {

  @Id
  @GeneratedValue
  @Column(name = "city_id")
  private Long cityId;

  @Column(name = "city_name")
  private String cityName;

  public Long getCityId() {
    return cityId;
  }

  public void setCityId(Long cityId) {
    this.cityId = cityId;
  }

  public String getCityName() {
    return cityName;
  }

  public void setCityName(String cityName) {
    this.cityName = cityName;
  }

}

JpaRepository 接口:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends JpaRepository<City, Long> {

    @Override
    List<City> findAll();
}

这是我的Contoller 课程

@RestController
@RequestMapping("/city")
public class CityController {
    @Autowired
    private CityRepository cityRepository;

    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<City> getAllCityList(){
        return cityRepository.findAll();
    }
}

我在这里做错了什么?参考文档:Spring doc

【问题讨论】:

  • 删除你覆盖的findAllJpaRepository中已经有一个,不需要再次添加它并禁用休眠模式创建,因为这基本上覆盖了schema.sql和@所做的工作987654337@.
  • @M.Deinum 我删除了 schema.sql 和 data.sql 并删除了覆盖的 findAll 方法,但它不起作用
  • 如果你删除这些文件,你显然不会插入任何东西......
  • @M.Deinum 我在 `application.properties` 文件中添加了`spring.jpa.hibernate.ddl-auto=update`,并将`schema.sql`和`data.sql`文件放入资源中再次。然后它起作用了!非常感谢。它拯救了我的一天:)

标签: java spring spring-data-jpa h2


【解决方案1】:

您有一个schema.sql 和data.sql,它们都在DataSource 配置并准备就绪后执行。接下来创建EntityManagerFactory,默认情况下(参见the reference guide)这将create-drop 用于嵌入类型(如H2)的数据库。

您可以通过将spring.jpa.hibernate.ddl-auto 属性更改为除create 或create-drop 之外的任何其他属性来覆盖此行为。

另一个解决方案是将您的 data.sql 重命名为 import.sql,这将在 Hibernate 为您创建架构后执行。您现在显然也可以删除schema.sql,因为 Hibernate 将创建模式。

如果这是出于学习目的,你应该没问题,如果你想在现场制作系统中使用它,我建议不要使用它来使用 Flyway 之类的东西来管理你的架构。

【讨论】:

    【解决方案2】:

    据我了解,您想在应用程序启动时执行 sql 脚本,然后使用 Hibernate?好吧,你必须使用here提到的选项之一,并设置spring.jpa.hibernate.ddl-auto=none。那里给出了解释。

    祝你好运

    【讨论】:

      【解决方案3】:

      在我的情况下,我将已删除的列设为 null,并在 JPA 实体上有 @Where(clause = "deleted='false'")

      【讨论】:

        【解决方案4】:

        这是一个适合我的示例代码:

        @DataJpaTest
        @TestPropertySource(properties = {
                "spring.datasource.schema=classpath:/sql/schema.sql",
                "spring.datasource.data=classpath:/sql/data.sql",
                "spring.jpa.hibernate.ddl-auto=none"
        })
        class CalculatorRepositoryTest implements WithAssertions {
        
            @Autowired
            private CalculatorRepository repository;
        
            @Test
            void testAutoConfiguration() {
                assertThat(repository).isNotNull();
            }
        
            @Test
            void testInsertResult() {
        
                Result newResult = new Result();
                newResult.setOperation(OperationType.DIVISION.name());
                newResult.setValue(10);
        
                Result insertedResult = repository.save(newResult);
        
                assertAll(
                        () -> assertThat(insertedResult).isNotNull(),
                        () -> assertThat(insertedResult.getId()).isEqualTo(5L),
                        () -> assertThat(insertedResult.getOperation()).isEqualTo(OperationType.DIVISION.name()),
                        () -> assertThat(insertedResult.getValue()).isEqualTo(10)
                );
            }
        
            @Test
            void testSelectAllResults() {
        
                List<Result> results = repository.findAll();
                assertAll(
                        () -> assertThat(results).isNotEmpty(),
                        () -> assertThat(results.get(0).getOperation()).isEqualTo(OperationType.ADDITION.name()),
                        () -> assertThat(results.get(0).getValue()).isEqualTo(5)
                );
        
            }
        
        }
        

        schema.sql

        CREATE TABLE result(
            id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
            operation VARCHAR(50) NOT NULL,
            value INT
        );
        

        data.sql

        INSERT INTO result(id, operation, value) VALUES(1, 'ADDITION', 5);
        INSERT INTO result(id, operation, value) VALUES(2, 'SUBTRACTION', 14);
        INSERT INTO result(id, operation, value) VALUES(3, 'MULTIPLICATION', 10);
        INSERT INTO result(id, operation, value) VALUES(4, 'DIVISION', 3);
        

        首先你不需要重写findAll() 方法。它已经在您的界面中可用。

        在配置您的schema.sql 和data.sql 文件时,首先要做的是将此属性spring.jpa.hibernate.ddl-auto 设置为none,以避免休眠为您创建架构。

        spring.datasource.schema=classpath:/sql/schema.sql
        spring.datasource.data=classpath:/sql/data.sql
        

        我的sql 文件位于此位置:test/resources/sql。否则,默认情况下,如果您将文件放在test/resources 中,则不需要这些配置

        您可以在此post 上找到非常好的详细信息。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-16
          • 1970-01-01
          • 1970-01-01
          • 2023-03-08
          • 2021-05-20
          • 2021-11-21
          • 1970-01-01
          • 2019-08-21
          相关资源
          最近更新 更多