Hibernate @OneToMany为空集

时间:2017-06-16 02:04:33

标签: spring hibernate spring-boot

请告诉我,我明白当你调用getOrders()时,必须返回完整的Set?

订单表中的FK。

或者您只需要使用HQL(JPQL)来获取Orders对象?

我变空了。 当我调用getter时设置orderSet = bid.getOrders();在调试中我不显示任何动作。

@Entity
@Table(name = "bid") 
public class Bid {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "bid_id",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Set<Order> orders = new HashSet<>();
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;


public Set<Order> getOrders() {
    return orders;
}

public void setOrders(Set<Order> orders) {
    this.orders = orders;
}

@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "title")
private String title;

@ManyToOne(optional = true,fetch = FetchType.EAGER,cascade = 
CascadeType.ALL)
@JoinColumn(name = "bid")
private Bid bid_id;

@Repository
@Transactional
public class BidDao {

@PersistenceContext
private EntityManager entityManager;

public void create(Bid bid){
    entityManager.persist(bid);
}

}

1 个答案:

答案 0 :(得分:0)

试试这个

  • 从一方到多方

    @OneToMany (targetEntity = Order.class, cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    
    @JoinColumn (name = "order_id", referencedColumnName = "id")
    
  • 从多方到一方

    @ManyToOne(targetEntity = Bid.class, optional = true,fetch = FetchType.EAGER,cascade =
            CascadeType.ALL)
    
    @JoinColumn(name = "order_id", referencedColumnName = "id")