2016-09-06 35 views
0

我有一個實體類,它只是一個具有額外的列一個多對多,如下所示:貯藏多對多額外列使用合併方法

@Entity 
@Table(name = "view_templates_device_types") 
public class ViewTemplateDeviceTypeEntity implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @ManyToOne 
    @JoinColumn(name = "view_template_id") 
    private ViewTemplateEntity viewTemplate; 

    @Id 
    @ManyToOne 
    @JoinColumn(name = "device_type_id") 
    private DeviceTypeEntity deviceType; 

    @Column(name = "priority", nullable = false) 
    private int priority; 

    public ViewTemplateDeviceTypeEntity() { 

    } 
    ... 
} 

我注意到,當我創建此類型的新對象,設置viewTemplate並將deviceType設置爲在數據庫中具有相應數據的值,我將這些數據存儲在entityManager.persist(entity)中。但是,當我打電話entityManager.merge(entity),而不是persist我得到一個異常:

SQL Error: 1048, SQLState: 23000
Column 'view_template_id' cannot be null

我想打電話合併不應導致它尚未存儲的情況下,插入到數據庫中的數據。這裏使用merge對我來說非常重要(因爲級聯)。我能做些什麼來使它工作?

+0

和你的'@ IdClass'? –

+0

嘗試在'@ JoinColumn'中定義'foreignKey = @ForeignKey(name =「constraint」)''。 –

+0

@BillyFrost我沒有'@ IdClass'因爲它似乎沒有必要。正如我所說的堅持工作正常。 – AjMeen

回答

0

按照JPA規範,第2.4節 "A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId or IdClass annotation is used to denote a composite primary key. See Sections 11.1.17 and 11.1.22.".

所以,你要麼需要@IdClass@EmbeddedId。其他任何東西都不可移植並且容易出錯。我非常驚訝於任何JPA提供商不會對此發出警告。