【问题标题】:How to query with Criteria API a base class?如何使用 Criteria API 查询基类?
【发布时间】:2020-08-05 19:54:00
【问题描述】:

实体如下所示:

@Entity
@Table(name = "user")
@Inheritance(
        strategy = InheritanceType.JOINED
)
public class User {

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

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

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

    @Enumerated(EnumType.STRING)
    @Column(name = "role", nullable = false)
    private UserRole userRole;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public UserRole getUserRole() {
        return userRole;
    }

    public void setUserRole(UserRole userRole) {
        this.userRole = userRole;
    }

}
@Entity
@Table(name = "customer")
public class Customer extends User {

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

    @Column(name = "consent_given", unique = false, nullable = false)
    private boolean consentGiven;

    @OneToOne(mappedBy = "customer",
            cascade = CascadeType.ALL,
            fetch = FetchType.LAZY)
    private Cart cart;

    @OneToMany(mappedBy = "customer",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private List<Order> orders = new ArrayList<>();

    @OneToOne(mappedBy = "customer", cascade = CascadeType.ALL,
            fetch = FetchType.LAZY)
    private Favorites favorites;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public boolean isConsentGiven() {
        return consentGiven;
    }

    public void setConsentGiven(boolean consentGiven) {
        this.consentGiven = consentGiven;
    }

    public void setCart(Cart cart) { this.cart = cart; }

    public Cart getCart() { return cart; }

    @Override
    public String toString() {
        return "Customer{" +
                "address='" + address + '\'' +
                ", consentGiven=" + consentGiven +
                ", cart=" + cart +
                ", orders=" + orders +
                ", favorites=" + favorites +
                '}';
    }

}
@Entity
@Table(name = "cart")
public class Cart {

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

    @OneToMany(cascade = CascadeType.ALL,
            orphanRemoval = true,
            fetch = FetchType.LAZY)
    @JoinColumn(name = "cart_id")
    private List<CartItem> listOfCartItems = new ArrayList<>();

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id")
    private Customer customer;

    @Column(name = "cart_total_price", unique = false)
    private double price;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public List<CartItem> getListOfCartItems() {
        return listOfCartItems;
    }

    public void setListOfCartItems(List<CartItem> listOfCartItems) {
        this.listOfCartItems = listOfCartItems;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double totalPrice) {
        this.price = totalPrice;
    }

}

我需要使用 Criteria API 通过客户 ID 获取购物车。
事情是,正如我所见,来自基类的主键将被 MySQL 中的客户类继承,即使它不是写在客户类中。
我的问题是,如果客户从基类继承主键,我如何查询 3 个表以通过他的 id 获取特定客户的购物车?
如果主键在客户的类中,我做了一个查询(即使它没有用):

Cart resultedCart;

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Cart> query = criteriaBuilder.createQuery(Cart.class);
Root<Cart> cart = query.from(Cart.class);
Join<Cart, Customer> customer = cart.join("customer");
ParameterExpression<Long> idParameter = criteriaBuilder.parameter(Long.class);
       
query.select(cart).where(criteriaBuilder.equal(customer.get("id"), idParameter));
TypedQuery<Cart> typedQuery = entityManager.createQuery(query);

try {
     resultedCart = typedQuery.setParameter(idParameter, id).getSingleResult();
} catch (NoResultException noResultException) {
     throw new NoCartFoundException("The searched cart does not exist!", noResultException);
} finally {
     entityManager.close();
}

return resultedCart;

我尝试根据此代码制作我需要的东西,但不幸的是,没有成功。

【问题讨论】:

    标签: java hibernate jpa criteria-api


    【解决方案1】:

    试试这个:

    Cart resultedCart;
    
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Cart> query = criteriaBuilder.createQuery(Cart.class);
    Root<Cart> cart = query.from(Cart.class);
    
    query.select(cart).where(criteriaBuilder.equal(cart.get("customer").get("id"), idParameter));
    
    TypedQuery<Cart> typedQuery = entityManager.createQuery(query);
    
    try {
         resultedCart = typedQuery.getSingleResult();
    } catch (NoResultException noResultException) {
         throw new NoCartFoundException("The searched cart does not exist!", noResultException);
    } finally {
         entityManager.close();
    }
    
    return resultedCart;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2015-02-21
      • 1970-01-01
      • 2021-10-13
      • 2011-10-17
      • 2012-11-28
      相关资源
      最近更新 更多