In case you want to execute named queries against an in memory DB with spring boot, you can use @DataJpaTest annotation.
It's pretty simple:
1) Include necessary dependencies in your pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>1.5.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
<version>1.4.194</version>
</dependency>
2) Annotate your test class:
@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(classes = InCaseYouWantConfigurationConfig.class)
public class TestDemo {
3) Autowire your repository or entity manager (for test):
@Autowired
private UserRepository userRepository;
@Autowired
private TestEntityManager entityManager;
4) Let's say you have a entity named user. Create one and use the entity manager to find it:
@Test
public void testNoDb() {
User user = new User();
user.setFirstName("First Name");
user.setLastName("Last name");
user.setUsername("username");
user.setPassword("password");
user.setEmail("[email protected]");
this.userRepository.save(user);
Query q = this.entityManager.getEntityManager().createQuery("SELECT u From User u WHERE u.username = :username",
User.class);
q.setParameter("username", "username");
User foundUser = (User) q.getSingleResult();
Assert.assertEquals("[email protected]", foundUser.getEmail());
}
In this case I use a normal query, but of course you could define a named query and use entityManager.createNamedQuery(...).