Reputation: 5
I have a list of persons in DB everyone having a CV field which is a MultiPart File in Spring. I'm trying to get all persons from db, but to ignore the CV field because I don't want to be downloaded when I use getAllPersons function. I saw a possibility with JsonIgnore but I want to ignore that field just in getAllPersons, not in other functions like getPersonById etc. How can I do it?
Upvotes: 0
Views: 1396
Reputation: 1821
You can also use DTO
as shown in below example:
Person entity:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@Entity
public class Person {
@Id
private long id;
private String name;
private String address;
@Lob
private Object cvFields;
}
PersonDTO:
package com.example.dto;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class PersonDTO {
private long id;
private String name;
private String address;
public PersonDTO(Person person) {
this.id = person.getId();
this.name = person.getName();
this.address = person.getAddress();
}
}
PersonRepository:
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query("SELECT new com.example.dto.PersonDTO(p) FROM Person p")
List<PersonDTO> getAll();
}
Upvotes: 0
Reputation: 5563
Suppose that you use Sping
and Spring-data
you can use a projection in order to avoid maintaining custom queries. Consider the following example:
Book
@Data
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(generator = "book_sequence", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "book_sequence", sequenceName = "book_sequence", allocationSize = 1)
private Long id;
@NaturalId
private String name;
private String author;
private String publisher;
private String plot;
@ManyToMany(mappedBy = "books")
@ToString.Exclude
@EqualsAndHashCode.Exclude
private Set<BookFilter> filters = new HashSet<>();
}
public interface BookNameAuthorOnly {
String getName();
String getAuthor();
}
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {
List<BookNameAuthorOnly> findBy();
}
When the latter is invoked, the dynamic query generated by Spring, will select only the fields that you have specified in the related interface
object. For more on this you can check the following documentation:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
Don't know if this fits your use case scenario but this is also another way of achieving what you need to achieve.
Upvotes: 0
Reputation: 3127
For that purpose you can use HQL.
i.e
interface Repo extends C... {
@Query(select h.name, h.phone, ... from Person h)
List<Person> getAllPerson();
}
Upvotes: 1