How to not return an specific column using PagingAndSortingRepository

三世轮回 提交于 2019-12-06 13:05:08

You need to use Projections for this purpose. It is documented in detail here

Create an interface with fields you want to include in the entity to be returned.
For example, in your case it would be like this

interface CarSummary {

  String getName();
  Long getId();
  UserSummary getUser();

  interface UserSummary {
    String getName();
    Long getId();
  }
}

and modify your repository like this

public interface CarRepository extends PagingAndSortingRepository<Car, Long> {
    Collection<CarSummary> findByOwner_name(String name);  
}

Projections can be used recursively. Something like this should work:

interface CarPojection{

      Long getId();
      String getName();
      UserSummary getUser();

      interface UserSummary {
        Long getId();
        String getName();
      }
    }

And your repository should return CarPojection Find more information in Spring docs: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

You can return a subset of data by providing a matching constructor in your entity class.

@Query("select new com.foo.bar.entity.User(u.id, u.name) from User u where u.name = ?1")
List<User> findByOwner_name(String name);

In you class User just provide the constructor and other properties will be left null:

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