Spring JPA - using entity field names in @Query annotation

4 points
Created by:

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.

Intellij IDEA intellicence hints with UserEntity field names


package com.dirask.repository;

import com.dirask.model.UserEntity;
import org.springframework.stereotype.Repository;

public interface UserRepository extends JpaRepository<UserEntity, Long> {

    @Query(value = "select u from UserEntity u where = ?1 and u.age = ?2")
    UserEntity findByNameAndAge(String name, int age);


package com.dirask.model;

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

@Table(name = "users")
public class UserEntity {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private int age;
    // constructor, getters, setters

Unit test

We can test if it works, download this project and copy repository method + query and run below unit test:

package com.dirask.repository;

import com.dirask.model.UserEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.assertj.core.api.Assertions.assertThat;

public class UserRepositoryTest {

    private UserRepository userRepository;

    public void should_find_one_user() {
        UserEntity user = userRepository.findByNameAndAge("Kate", 26);
        // User{id=1, name='Kate', age=26}
Unit test result

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


Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!

Java Persistence API (JPA)

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂