jeudi 4 mai 2017

How to set hibernate mapping resources in spring boot integration test

I am using spring boot with multiple data sources and hibernate.

In one of my DB configuration class, I set my mapping resources like below:

@Bean
public LocalContainerEntityManagerFactoryBean sqlEntityManager() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(sqlDataSource());
    em.setMappingResources("queries/city-named-queries.xml");

And here is city-named-queries.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="1.0" xmlns="http://ift.tt/1kiyE1j"
             xmlns:xsi="http://ift.tt/ra1lAU"
             xsi:schemaLocation="http://ift.tt/1kiyE1j http://ift.tt/1u10T7i">
<named-query name="City.getCityNameById">
    <query>
        <![CDATA[ SELECT c.name from City c WHERE c.id = :cityId ]]>
    </query>
</named-query>
</entity-mappings>

Repository:

public interface CityEntityRepository extends JpaRepository<CityEntity, Long> { @Query(name = "City.getCityNameById") String getTestMethodName(@Param("cityId") Long cityId); }

My mappings work fine with these settings above but in my integration test, I am getting an error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cityEntityRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property getTestMethodName found for type CityEntity!

@RunWith(SpringRunner.class)
@DataJpaTest
public class CityEntityRepositoryIT extends AbstractTransactionalModelSpringBootWiredIT {

@Autowired
private CityEntityRepository cityEntityRepository;

@Test
public void test() {
    CityEntity city = new CityEntity();
    city.setName("Amsterdam");
    entityManager.persist(city);
    CityEntity cityEntityActual = cityEntityRepository.getTestMethodName(city.getId());

    assertThat(cityEntityActual.getName()).isEqualTo("Amsterdam");
}

@ContextConfiguration(classes = TestDomainApplicationContext.class,
    loader = SpringBootContextLoader.class)
public class AbstractTransactionalModelSpringBootWiredIT {

@Autowired
protected TestEntityManager entityManager;
}

@Configuration
@AutoConfigureTestEntityManager
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@ComponentScan(value="com.xx.repository")
public class TestDomainApplicationContext {

@Bean
@ConfigurationProperties
@ConditionalOnMissingBean
public DataSource dataSource() {
    HikariConfig cfg = new HikariConfig();
    cfg.setDriverClassName("org.h2.Driver");
    cfg.setJdbcUrl("jdbc:h2:mem:;MODE=PostgreSQL");
    return new HikariDataSource(cfg);
}

}

It seems spring try to query based on the method name, not the mapped named queries and I need to define somewhere in the test to say spring to resolve my named queries but I don't know where and how! Any help, please?

Aucun commentaire:

Enregistrer un commentaire