Home > Blockchain >  How use projections in spring-data-jpa?
How use projections in spring-data-jpa?

Time:04-26

I need to get all the information about the ticket in one request, also the name, author, and year of the book. I have implemented this : I create interface TicketWithBookView

public interface TicketWithBookView {
    Date getGiveAway();
    Long getReaderId();
    Date getTake();

    interface Book {
        String getAuthor();
        String getName();
        Integer getYearCreation();
    }
}

My entities TicketEntity

@Data
@Entity
@Table(name = "ticket")
@NoArgsConstructor
@AllArgsConstructor
public class TicketEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false)
    private Long readerId;
    @Column(nullable = false)
    private Long bookId;
    @Column(nullable = false)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private Date take;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    private Date giveAway;
}

And second entity BookEntity;

@Entity
@Data
@NoArgsConstructor
@Table(name = "book")
public class BookEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String author;
    private Integer yearCreation;
    private Integer count;
}

And repository

@Repository
public interface TicketRepository extends CrudRepository<TicketEntity, Long> {
    List<TicketWithBookView> findAllByGiveAwayIsNullAndTakeIsNotNull();
}

CodePudding user response:

No way) Projections are used to select data from a query, and not to obtain data from other tables. You can upload data from another table and create a new model in the service.

CodePudding user response:

probably problem is with AAnd in method name

findAllByGiveAwayIsNullAAndAndTakeIsNotNull

add error message that you get, It would be easier to find problem

  • Related