【问题标题】:Hibernate @OneToMany empty setHibernate @OneToMany 空集
【发布时间】:2017-11-18 15:59:51
【问题描述】:

请正确告诉我,我理解当你调用 getOrders() 时,必须返回完整的 Set?

订单表中的 FK。

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

我得到了空集。 当我调用 getter Set 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);
}

}

【问题讨论】:

  • 是的,它应该返回完整集。请展示你如何在 dao 级别获得 Bit?
  • 嗯,在 dao 我只创建,但在控制器 Set orderSet = bid.getOrders(); 中调用 getter;
  • Entity 的创建/读取/更新/删除操作应该在Repository 中,而不是在Controller 中。

标签: spring hibernate spring-boot


【解决方案1】:

试试这个

  • 从一到多

    @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")
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多