spring-data-jpa DataJpaTest无法与mysql全文搜索一起使用

relj7zay  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(119)

我正在试着检验这个方法:

@Query(value = "select *  from table "
+ "where match(name_column) AGAINST(:name in BOOLEAN MODE)", nativeQuery = true)

List<ManagedGroup> findByGroupNameMatches(@Param("name") String groupName);

测试本身:

@Test
  public void findByGroupNameMatches_should_return_when_contains_part_of_name(){
    ManagedGroup managedGroup = prepearGroup(UUID.randomUUID().toString());
    managedGroup.setGroupName("def123");
    testEntityManager.persistAndFlush(managedGroup);

    // in desperate tries - tried to save it via repositroty as well
    groupRepository.save(managedGroup);

    //the groups can be found - there is two groups with names 'def123' and 'default name'
    List<ManagedGroup> res =  groupRepository.findAll();
    Pageable pageable = new OffsetLimitPageRequest(0, 10,  Sort.by(Sort.Direction.DESC, "id"));

    List<ManagedGroup> managedGroupPage = groupRepository.findByGroupNameMatches("+def*");
     //managedGroupPage is empty after the method is called
    Assertions.assertEquals(defaultManagedGroup, managedGroupPage.get(0));
  }

测试失败,因为我从findByGroupNameMatches得到空的结果。我尝试过通过jdbcTemplate保存和检索实体-仍然没有结果。其他测试也可以工作,所以我猜这不是问题所在。
该方法在已实现的控制器中工作,并已由QA团队进行了测试。
我也尝试过对QA数据库运行测试,它使用实体,在测试启动前持久化。我确信问题出在持久化上,但我仍然找不到解决方案。我尝试了不同的flush等组合,但仍然没有结果
提供更多信息以重现测试:

static final MySQLContainer DATABASE = new MySQLContainer("mysql:8.0.23");

  static {
    DATABASE.start();
  }

  static class Initializer implements
      ApplicationContextInitializer<ConfigurableApplicationContext> {
    public void initialize(ConfigurableApplicationContext context) {
      TestPropertyValues.of(
          "spring.datasource.url=" + DATABASE.getJdbcUrl(),
          "spring.datasource.username=" + DATABASE.getUsername(),
          "spring.datasource.password=" + DATABASE.getPassword()
      ).applyTo(context.getEnvironment());
    }

测试类使用

@DataJpaTest
@ExtendWith(SpringExtension.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@DisabledIfEnvironmentVariable(named = "RUN_INTEGRATION_TEST", matches = "false")
@DirtiesContext
  }
hk8txs48

hk8txs481#

您好,您不应该为此本机查询提供表名吗

@Query(value = "select *  from table TABLE_NAME "
+ "where match(name_column) AGAINST(:name in BOOLEAN MODE)", nativeQuery = true)

List<ManagedGroup> findByGroupNameMatches(@Param("name") String groupName);

此外,当事务性注解不存在时,还应刷新

// in desperate tries - tried to save it via repositroty as well
    groupRepository.save(managedGroup);

请使用groupRepository.flush或保存并刷新

相关问题