如何在Hibernate中只保存子类相关数据

时间:2014-05-11 17:03:09

标签: hibernate persistence

我有以下课程

  1. 具体类项目

    @Entity
    @Table(name = "ITEM")
    @Inheritance(strategy= InheritanceType.JOINED)
    Class Item implements Serializable {        
      private static final long serialVersionUID = 1L;
      @Id
      @Column(name = "NAME")
      private final String name;
      @Column(name = "PRICE")
      private BigDecimal price;
    }
    
  2. 扩展Item

    的具体类AddedItem
    @Entity
    @Table(name = "ADDED_ITEM")
    @PrimaryKeyJoinColumn(name = "NAME")
    public class AddedItem extends Item {
       @Column(name = "TOTAL_PRICE")
       private BigDecimal totalPrice;
       @Column(name = "QUANTITY")
       private Integer quantity;
       @ManyToOne
       @JoinColumn(name = "INVOICE_ID")
       private Invoice invoice;
     }
    
  3. 与AddedItem

    具有一对多映射的Invoice类
    @Entity
    @Table(name = "INVOICE"
    public class Invoice implements Serializable {
    
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "INVOICE_ID")
      private Long billNo;
      @Column(name = "BILLDATE")
      @Temporal(TemporalType.TIMESTAMP)
      private Date billDate;
      @Column(name = "CUSTOMERNAME")
      private String customerName;
      @OneToMany(fetch = FetchType.LAZY, mappedBy = "invoice", cascade = CascadeType.ALL)
      private final List<AddedItem> itemsAdded;
    }
    
  4. 当我尝试保存Invoice实例时,我收到以下异常:

    org.hibernate.util.JDBCExceptionReporter logExceptions
    SEVERE: ORA-00001: unique constraint (ITEM_PK) violated
    
    org.hibernate.event.def.AbstractFlushingEventListener performExecutions
    SEVERE: Could not synchronize database state with session
    org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch      update
    ...
    

    当我预取Item相关信息时,如何告诉Hibernate只存储子类信息?

1 个答案:

答案 0 :(得分:0)

@Inheritance(strategy= InheritanceType.JOINED)中,您必须定义@DiscriminatorColumn 确定行的类。添加它可以解决问题。如果您正在使用Hibernate 3.1或更低版本(希望您不是),@DiscriminatorFormula应该完成这项工作,但我从未亲自尝试过。

接下来在AddedItem实体上,@PrimaryKeyJoinColumn(name = "NAME")javadocstackoverflow几乎只是为了展示,但它不会造成任何伤害。

如果AddedItem是公开的,那么Item实体应该是公开的。

编辑:由于您的ID字段是字符串,您确定要使用正确的唯一值吗?