Exclude column from resultset in controller | Spring data jpa
Use @JsonIgnore, this will make it available in the back but will not return when transforming to json
@Size(min = 8)
@JsonIgnore
private String password;
You can use @Query
to selectively include some fields:
// Include all fields you wanna query for using u.x syntax
// AFAIK there is no exclusion syntatic sugar
@Query("select u.id, u.username from SpringUsers u where u.id = ?1")
List<SpringUsers> findByUserId(Integer userId);
Also you can use Projections. First define the projection by introducing a projection interface:
interface NoPasswordUser {
Long getId();
String getUsername();
// Do not include getPassword();
}
Then use it in your repository:
public interface SpringUsersRepository extends CrudRepository<SpringUsers, Integer> {
NoPasswordUser findByUsername(String username);
List<NoPasswordUser> findByUserId(Integer userId);
}
Anyway, It's better to not expose your entities through a REST or any remote interface. You can use DTOs for that matter, this post may be useful in this area.
I don't think there is a way to just ignore some fields when getting the entity from db, because those entities wouldn't be in a consistent state - their data would differ from the data in the database. Other options exist, though (custom query, projections).
One option is to use constructor expressions and fill some POJO with only needed data in the query directly
select new my.company.SafeUser(u.username, u.email) from User u
Anyway, I think you should send DTOs to the frontend, and in it expose just the attributes you need on the frontend. That approach has much advantages, weather you initialize them like in the example above, or in the loop over results.