简体   繁体   中英

Executing the NOT IN QUERY for objects with Many to Many relationships in JPA

I have two JPA objects namely Product and Order that have a many to many relationship with each other.

@Entity
@Table(name = "orders")
@JsonInclude(NON_NULL)
public class Order implements Serializable {

    public static final int PRECISION = 2;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @JsonIgnore
    private String orderId;

    @Column(unique = true, nullable = false, length = 8)
    private String orderNumber;

    @Column
    private BigDecimal discount;

    @Column(nullable = false)
    private BigDecimal taxPercent;

    private BigDecimal total;

    private BigDecimal totalTax;

    private BigDecimal grandTotal;

    @Column(length = 10)
    private String status;

    @ManyToMany(cascade = ALL, fetch = FetchType.EAGER)
    @JoinTable(
            name = "order_product",
            joinColumns = @JoinColumn(name = "order_id", updatable = false, nullable = false),
            inverseJoinColumns = @JoinColumn(name = "product_id", updatable = false, nullable = false)
    )
    private List<Product> products = new ArrayList<>();

    public BigDecimal getTotal() {
        BigDecimal total = new BigDecimal(ZERO);
        if (products == null || products.isEmpty()) {
          return total;
        }
        for (Product product : products) {
            total = total.add(product.getPrice());
        }
        return scaled(total);
    }

    public BigDecimal getTotalTax() {
        return scaled(getTotal().multiply(taxPercent.divide(new BigDecimal("100"))));
    }

    public BigDecimal getGrandTotal() {
        BigDecimal total = this.getTotal().add(getTotalTax());
        if (discount != null) {
            return scaled(total.subtract(discount));
        }
        return scaled(total);
    }

    private BigDecimal scaled(BigDecimal value) {
        return value.setScale(PRECISION, ROUND_FLOOR);
    }

    .. Getters and setters ... 

}

and Product

@Entity
@Table(name = "products")
public class Product implements Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @JsonIgnore
    private String productId;

    @Column(unique = true, nullable = false, length = 10)
    private String upc;

    @Column(unique = true, nullable = false, length = 13)
    private String sku;

    @Column(nullable = false)
    private String description;

    @Column(nullable = false)
    private BigDecimal price;

    public BigDecimal getPrice() {
      return price;
    }

    @ManyToMany(mappedBy="products", fetch=FetchType.EAGER)
    @JsonIgnore
    private List<Order> orders = new ArrayList<>();

    // Getters and setters.
}

This is my DML

insert into products (product_id, upc, sku, description, price) values ('1', '1257833283', '9394550220002', 'Diva Jeans', 39.99);
insert into products (product_id, upc, sku, description, price) values ('2', '1358743283', '7394650110003', 'Polo Shirt', 19.99);
insert into products (product_id, upc, sku, description, price) values ('3', '1458843283', '7394750120000', 'Floral Swing Skirt', 69.99);
insert into products (product_id, upc, sku, description, price) values ('4', '1358753283', '7394850130001', 'Denim Short', 29.99);
insert into products (product_id, upc, sku, description, price) values ('5', '1258793283', '7394950140000', 'True Skinny Jeans', 49.99);

insert into orders (order_id, order_number, tax_percent, status) values ('1', 'RTL_1001', 10, 'SHIPPED');
insert into orders (order_id, order_number, discount, tax_percent, status) values ('2', 'RTL_1002', 15.55, 10, 'FULFILLED');


insert into order_product (order_id, product_id) values ('1', '1');
insert into order_product (order_id, product_id) values ('1', '2');
insert into order_product (order_id, product_id) values ('2', '2');

I want to select only those product such that

  1. If I query for products by order that does not exist (say with order_id = 3 which does not exist), I want to return all the eligible products as the order has not been created yet.

  2. If I query for products by order that does exist, then I want the database to return all products not associated with the order. For example for order_id = 1 , I want the products with id = 3, 4 and 5 to be returned. Since order_id = 1 is already associated to product_id = 1, and 2, I don't want these products to be returned.

If I were to write a JDBC SQL query

SELECT p.product_id
FROM Product p
WHERE NOT EXISTS 
    (
        SELECT 1 
        FROM order_product 
        WHERE product_id = p.product_id
            AND
            order_id = ?
    )
    OR 
    NOT EXISTS
    (
        SELECT 1 
        FROM order_product 
        WHERE order_id = ?
    )

I don't know how to use JPA to create a similar query. All I can think of is something like this.

  1. Create a ProductRepository that inherits from JPARepository

  2. Fetch all products from Product Table including the ones in the order_product table.

  3. Fetch the products for a given order id with JPA and remove the said products from the products in (2)

I am hoping that there is a better way to do so.

Order order = em.getReference(Order.class, orderId);
em.createQuery("select distinct p from Product p where :order not member of p.orders")...;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM