休眠-第二组实体

时间:2019-07-17 14:27:51

标签: java hibernate

我有此代码:

Map<OrderProduct, Product> temp = 

session.createQuery("FROM OrderProduct " +
                    "WHERE orderId = '" + orderId + "'", OrderProduct.class)
        .getResultList()
        .stream()
        .collect(Collectors.toMap(
                                k -> k,
                                v -> session.createQuery("FROM Product " +                                                       
                                                         "WHERE id = '" + v.getProductId() + "'", Product.class)                                                                                                            
                                             .getSingleResult())); 

在这里,我接受了特定订单(order products)的所有orderId

创建流后,将其收集为Map

在按键order products上输入一个值,然后再次查询以获取product(产品信息)。

现在,我对每个order product进行2个查询。有一种方法可以通过单个查询来实现所有这些功能?

类似的东西:

SELECT * 
FROM order_products OP, products P
WHERE OP.product_id = P.id;

但是我不知道如何在休眠中使用。

以下是实体:

@Entity

@Table(name = "order_products")
public class OrderProduct{

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

    @Column(name = "order_id")
    private Integer orderId;

    @Column(name = "product_id")
    private Integer productId;

    @Column(name = "quantity")
    private Integer quantity;

    //getters setters

}

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

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

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

    //getters setters

}

以下是有关数据库外观的简短示例:

OrderProduct:
id-----order_id-----product_id-----quantity
1------1------------1--------------2
2------1------------2--------------1
3------2------------1--------------1

Product:
id-----name
1------productOne
2------productTwo

1 个答案:

答案 0 :(得分:1)

对于多对一关系:

将您的实体更改为此:

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

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

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

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "product", cascade = { CascadeType.ALL })
    private List<OrderProduct> orderProducts = new ArrayList<OrderProduct>();

    //getters setters

}

@Entity
@Table(name = "order_products")
public class OrderProduct{

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

    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    @JoinColumn(name = "product_id")
    private Product product;

    @Column(name = "quantity")
    private Integer quantity;

    //getters setters

}

现在输入代码:

int orderId = 1; // put any id
OrderProduct orderProduct = session.get(OrderProduct.class, orderId);
System.out.println(orderProduct.getProduct().getId());

希望这对您有所帮助。 :)