EN
Spring JPA - using entity field names in @Query annotation
4 points
In this post I would like to share that we can use entity field names in @Query annotations when we build new SQL query. Intellij IDEA will help us with intellicence. Entity needs to have getters.

Repository:
xxxxxxxxxx
1
package com.dirask.repository;
2
3
import com.dirask.model.UserEntity;
4
import org.springframework.data.jpa.repository.JpaRepository;
5
import org.springframework.data.jpa.repository.Query;
6
import org.springframework.stereotype.Repository;
7
8
9
public interface UserRepository extends JpaRepository<UserEntity, Long> {
10
11
value = "select u from UserEntity u where u.name = ?1 and u.age = ?2") (
12
UserEntity findByNameAndAge(String name, int age);
13
}
Entity:
xxxxxxxxxx
1
package com.dirask.model;
2
3
import javax.persistence.Entity;
4
import javax.persistence.GeneratedValue;
5
import javax.persistence.GenerationType;
6
import javax.persistence.Id;
7
import javax.persistence.Table;
8
9
10
name = "users") (
11
public class UserEntity {
12
13
14
strategy = GenerationType.IDENTITY) (
15
private Long id;
16
17
private String name;
18
private int age;
19
20
// constructor, getters, setters
21
}
Unit test
We can test if it works, download this project and copy repository method + query and run below unit test:
xxxxxxxxxx
1
package com.dirask.repository;
2
3
import com.dirask.model.UserEntity;
4
import org.junit.Test;
5
import org.junit.runner.RunWith;
6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
8
import org.springframework.test.context.junit4.SpringRunner;
9
10
import static org.assertj.core.api.Assertions.assertThat;
11
12
SpringRunner.class) (
13
14
public class UserRepositoryTest {
15
16
17
private UserRepository userRepository;
18
19
20
public void should_find_one_user() {
21
UserEntity user = userRepository.findByNameAndAge("Kate", 26);
22
assertThat(user).isNotNull();
23
// User{id=1, name='Kate', age=26}
24
System.out.println(user.toString());
25
}
26
}

TODO: make repo on github with this exampe based on repo: