График сущности JPA Spring Data, выбирающий все поля - PullRequest
0 голосов
/ 12 апреля 2020

Я пытаюсь разработать API поиска, для которого мне не нужно выбирать каждый столбец в таблицах. Могут быть некоторые критерии для фильтрации, и я использую для этого CriteriaBuilder. Затем я определил NamedEntityGraph и его подграфы для выбора нужных мне столбцов c. Но я что-то упускаю и не могу найти, что это такое. Потому что всякий раз, когда я выполняю запрос, он выбирает все значения объекта.

@NamedEntityGraph(name = "graph.Bill",
    attributeNodes = {
        @NamedAttributeNode(value = "id"),
        @NamedAttributeNode(value = "invoiceName"),
        @NamedAttributeNode(value = "creationDate"),
        @NamedAttributeNode(value = "products", subgraph = "subGraph.Product"),
        @NamedAttributeNode(value = "customer", subgraph = "subGraph.Customer"),
        @NamedAttributeNode(value = "user", subgraph = "subGraph.User")
    },
    subgraphs = {
        @NamedSubgraph(
            name = "subGraph.Product",
            attributeNodes = {
                @NamedAttributeNode(value = "quantity"),
                @NamedAttributeNode(value = "taxPercentage"),
                @NamedAttributeNode(value = "rate")
            }
        ),
        @NamedSubgraph(
            name = "subGraph.Customer",
            attributeNodes = {
                @NamedAttributeNode(value = "name")
            }
        ),
        @NamedSubgraph(
            name = "subGraph.User",
            attributeNodes = {
                @NamedAttributeNode(value = "name")
            }
        )
    }
)
@Entity
@Table(name = "BILL")
@Getter
@Setter
public class Bill implements Serializable {

    private static final long serialVersionUID = 8630090438139938349L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    Long id;

    @Column(name = "INVOICE_NAME", unique = true)
    private String invoiceName;

    @Temporal(TemporalType.DATE)
    private Date creationDate;

    @OneToMany(mappedBy = "bill", cascade = CascadeType.ALL)
    private Set<Product> products;

    @ManyToOne
    private User user;

    @ManyToOne
    private Customer customer;

    @Enumerated(EnumType.STRING)
    @Column(name = "BILL_TYPE")
    private BillType billType;

}
@Entity
@Table(name = "Product")
@Getter
@Setter
@ToString
public class Product implements Serializable {

    private static final long serialVersionUID = -6548945007368293623L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    @Column(name = "Description", nullable = false)
    private String description;

    @Column(name = "HSN_CODE", nullable = false)
    private String hsnCode;

    @Column(name = "QUANTITY", nullable = false)
    private Integer quantity;

    @Column(name = "TAX_PERCENTAGE", nullable = false)
    private Integer taxPercentage;

    @Column(name = "RATE", nullable = false)
    private Double rate;

    @Enumerated(EnumType.STRING)
    @Column(name = "PER_VALUE")
    private PerValue perValue;

    @ManyToOne(optional = false, targetEntity = Bill.class)
    @JsonIgnore
    private Bill bill;

}
@Entity
@Table(name = "CUSTOMER")
@Getter
@Setter
@ToString
public class Customer implements Serializable {

    private static final long serialVersionUID = 3719750814154703990L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private Long id;

    @Column(name = "CITY")
    private String city;

    @Column(name = "GST_NO", unique = false, length = 15)
    @Pattern(regexp = "^[0-9]{15}$")
    private String gstNo;

    @Column(name = "NAME", unique = true, nullable = false)
    private String name;

    @Column(name = "PHONE_NUMBER", unique = true, length = 10)
    @Pattern(regexp = "^[0-9]{10}$")
    private String phoneNumber;

    @Column(name = "STREET")
    private String street;

    @Column(name = "STATE")
    private String state;

    @Column(name = "ZIP_CODE")
    private String zipCode;

    @Enumerated(EnumType.STRING)
    @Column(name = "CUSTOMER_TYPE", nullable = false)
    private CustomerType customerType;

}

@Entity
@Table(name = "USER")
@Getter
@Setter
@ToString
public class User implements Serializable {

    private static final long serialVersionUID = -2432216802067413443L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "USER_NAME", unique = true)
    private String userName;

    @Column(name = "EMAIL_ID", unique = true)
    private String emailId;

    @Column(name = "PASSWORD")
    private String password;

    @Enumerated(EnumType.STRING)
    @Column(name = "ROLE")
    private UserRole role;

}

@Service
public class BillServiceImpl {

    @Autowired
    private EntityManager entityManager;

    public List<Bill> search(BillRequest billRequest) {

        List<Predicate> predicates = new ArrayList<>();
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();

        CriteriaQuery<Bill> criteriaQuery = criteriaBuilder.createQuery(Bill.class);
        Root<Bill> billRoot = criteriaQuery.from(Bill.class);

        if (!Utils.isNullOrEmpty(billRequest.getInvoiceNumber())) {
            predicates.add(criteriaBuilder.equal(billRoot.get("invoiceName"), billRequest.getInvoiceNumber()));
        } else {
            if (Objects.nonNull(billRequest.getCustomer()) && Objects.nonNull(billRequest.getCustomer().getId())) {
                predicates.add(
                        criteriaBuilder.equal(billRoot.get("customer").get("id"), billRequest.getCustomer().getId()));
            }
            if (Objects.nonNull(billRequest.getStartDate()) && Objects.nonNull(billRequest.getEndDate())) {
                predicates.add(criteriaBuilder.between(billRoot.get("creationDate"), billRequest.getStartDate(),
                        billRequest.getEndDate()));
            }
        }
        criteriaQuery.where(predicates.toArray(new Predicate[] {}));
        EntityGraph<?> entityGraph = entityManager.getEntityGraph("graph.Bill");

        TypedQuery<Bill> typedQuery = entityManager.createQuery(criteriaQuery).setHint("javax.persistence.fetchgraph",
                entityGraph);

        return typedQuery.getResultList();
    }

    @Override
    public List<SearchBillResponse> searchBills(BillRequest billRequest) {
        List<SearchBillResponse> billResponses = new ArrayList<>();
        List<Bill> billList = search(billRequest);
        if (Utils.isNullOrEmpty(billList)) {
            throw new CommonException("No records found");
        }
        billList.stream().forEach(bill -> {
            SearchBillResponse billResponse = new SearchBillResponse();
            billResponse.setId(bill.getId());
            billResponse.setCustomerName(bill.getCustomer().getName());
            billResponse.setDate(bill.getCreationDate());
            billResponse.setInvoice(bill.getInvoiceName());
            billResponse.setPlace(bill.getCustomer().getCity());
            billResponse.setInvoiceAmount(getInvoiceAmount(bill));
            billResponse.setUserName(bill.getUser().getName());
            billResponses.add(billResponse);
        });
        return billResponses;
    }

}
@Getter
@Setter
@NoArgsConstructor
public class SearchBillResponse implements Serializable {

    /**
     * SerialVersionUID
     */
    private static final long serialVersionUID = 8738959121083602890L;

    private Long id;
    private String customerName;
    private String place;
    private String invoice;
    @JsonDeserialize(using = CustomDateDeSerializer.class)
    @JsonSerialize(using = CustomDateSerializer.class)
    private Date date;
    private String invoiceAmount;
    private String userName;

}

@Getter
@Setter
@ApiModel
public class BillRequest {

    Boolean isAllBillRequest;

    @JsonDeserialize(using = CustomDateDeSerializer.class)
    @JsonSerialize(using = CustomDateSerializer.class)
    Date startDate;

    @JsonDeserialize(using = CustomDateDeSerializer.class)
    @JsonSerialize(using = CustomDateSerializer.class)
    Date endDate;

    Customer customer;

    String invoiceNumber;

}

Пожалуйста, помогите мне, что на что часть, которую я пропускаю. Полный код на GitHub

...