具有额外列的多对多只返回一行

时间:2017-04-26 10:43:21

标签: java spring hibernate jpa spring-data

我有Order's,其中包含一堆Product's和一个数量。

我的Order实体:

@Entity(name = "orders") // Select * from order order by... NO!
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @OneToMany(mappedBy = "product", cascade = ALL, orphanRemoval = true, fetch = EAGER)
    private List<OrderEntity> orderEntities = new ArrayList<>();
...

ordersproducts之间的关系如下:

@Entity
public class OrderEntity implements Serializable {
    @Id
    @ManyToOne
    @JsonIgnore
    private Order order;

    @Id
    @ManyToOne(fetch = EAGER)
    private Product product;

    private int quantity;
...

我的product如下:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderEntity> orderEntity;
...

问题在于,当我选择order id时我只会得到一个OrderEntity,即使我可以看到有几个与order相关联通过查看数据库表。任何人都知道我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为你实际配置了mappedBy incoretly ..反过来。

所以你应该这样:

订单:

@Entity(name = "orders") // Select * from order order by... NO!
public class Order {

    @OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true, fetch = EAGER)
    private List<OrderEntity> orderEntities = new ArrayList<>();

产品:

@Entity
public class Product {

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderEntity> orderEntity;