manyToMany hibernate映射的计数不正确

时间:2018-04-19 14:06:19

标签: java hibernate many-to-many

我在两个实体之间存在双向关系:Item(15条记录)和maintenanceContract(22条记录)

映射表item_maintenanceContract链接这两个实体包含25条记录

我想计算maintenanceContract表中的记录,然后运行以下查询:

“SELECT count(*)FROM MaintenanceContract mc LEFT JOIN mc.items as i”

不幸的是,我想象的是25而不是想要的22。 我不能简单地依靠MaintenanceContract,因为当我根据项目属性执行相同的搜索时,需要使用Item连接。

我尝试了其他组合:LEFT JOIN,左外连接,右连接......结果没有变化

我缺少什么?

我的项目定义:

@Entity
@Table(name = "item"})
@Inheritance(strategy = InheritanceType.JOINED)
public class Item extends BaseEntity implements Serializable {

  private Long id;
  private Set<MaintenanceContract> maintenanceContracts = new HashSet<MaintenanceContract>(0);

  @Id
  @GeneratedValue(strategy = IDENTITY)

  @Column(name = "id", unique = true, nullable = false)
  public Long getId() {
    return this.id;
  }

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

  @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JoinTable(name = "item_maintenancecontract", joinColumns = {
      @JoinColumn(name = "item_id", nullable = false, updatable = false)},
      inverseJoinColumns = {@JoinColumn(name = "maintenancecontract_id",
          nullable = false, updatable = false)})

  public Set<MaintenanceContract> getMaintenanceContracts() {
    return maintenanceContracts;
  }

  public void setMaintenanceContracts(Set<MaintenanceContract> maintenanceContracts) {
    this.maintenanceContracts = maintenanceContracts;
  }

}

和我的MaintenanceContract

@Entity
public class MaintenanceContract implements Serializable {

  private Long id;
  private Set<Item> items = new HashSet<Item>(0);

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  public Long getId() {
    return id;
  }

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

  @ManyToMany(fetch = FetchType.EAGER, mappedBy = "maintenanceContracts")
  public Set<Item> getItems() {
    return this.items;
  }

  public void setItems(Set<Item> items) {
    this.items = items;
  }

}

0 个答案:

没有答案