Select one column using Spring Data JPA

给你一囗甜甜゛ 提交于 2019-12-01 15:18:13

This Works for me.

public interface UserDataRepository extends JpaRepository<UserData, Long> {

    @Query(value = "SELECT emp_name FROM user_data", nativeQuery = true)
    public List<Object[]> findEmp_name();
}


System.out.println("data"+  userDataRepository.findEmp_name());

The above line gave me this result :

data[abhijeet, abhijeet1, abhijeet2, abhijeet3, abhijeet4, abhijeet5]

Ethiraj

Concept is : In your entity class create a constructor with only required instant variables. And use that constructor in the repository method shown below.

Lets say you have a interface Repository like below

  1. Repository implementation:

    public interface UserRepository<User> extends JpaRepository<User,String>
    {
        @Query(value = "select new com.org.User(usr.userId) from User usr where usr.name(:name))")
        List<User> findUserIdAlone(@Param("name") String user);
    }
    
  2. In Controller

    @RestController
    public class UserController 
    {
        @Autowired
        private UserRepository<User> userRepository; 
    
        @Res
        public ResponseEntity<User> getUser(@PathVariable("usrname") String userName)
        {
            User resultUser = usrRepository.findUserIdAlone(userName);
            return ResponseEntity.ok(resultUser);
        }
    }
    
    public class User 
    {
    
        private String userId,userName;
    
        public User(String userId) 
        {
            this.userId=userId;
        }
        // setter and getters goes here
    }
    

If you want to only return a single column you should look at Projections and Excerpts which will allow you to filter specific columns and other things that are usefule.

If you need list all of the users, try select userName from Users, if you need one user use "where" look at spring data JPA http://docs.spring.io/spring-data/jpa/docs/current/reference/html/ , try change CrudRepository to JpaRepository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!