要在另一个实体中引用的复合键的一个Id

时间:2014-01-21 07:45:21

标签: java hibernate jpa

  • 表1只有两列,形成一个复合键。
  • 正在生成表2 id列。
  • 我提供的Table1的一个属性的值,对于第二个属性,我需要它来获取Table2的生成值。 以下是我到目前为止的情况 -

复合主键:

public class PKClass implements Serializable
{
    private static final long serialVersionUID = -2092390836751020965L;
    public PKClass(){}
    public PKClass(long actId, long actAttId){
        this.actvId = actId;
        this.actvAtId = actAttId;
    }

    private long actvId;
    private long actvAtId;
    // getters, setters, equals, hashcode
}

实体类1:

@Entity @Table(name = "Table1")
@IdClass(PKClass.class)
public class AtLinkData implements Serializable
{
    @Id @Column(name = "ACT_ID", nullable = false)
    private long actvId;
    @Id @Column(name = "ACT_AT_ID")
    private long actvAtId;
    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, , mappedBy = "atLinkData")
    @JoinColumn(name = "ACT_AT_ID")
    private AtData atData;
    // getters, setters
}

实体类2:

@Entity @Table(name = "Table2")
public class AtData implements Serializable
{
    @TableGenerator(name = "somename", table = "sometable", pkColumnName = "somecolumn", valueColumnName = "valuename", pkColumnValue = "Table2", allocationSize = 1)
    @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "somename")
    @Column(name = "ACT_AT_ID")
    private Long id;
    // other variables
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ACT_AT_ID")
    private AtLinkData atLinkData;
    // getters setters
}

我一直在尝试不同的东西,但是上面的代码,我收到了错误:

Caused by: org.hibernate.MappingException: broken column mapping for: atLinkData.id of: com.test.database.AtData

2 个答案:

答案 0 :(得分:4)

@OneToOne(的mappedBy = “活动促销”) 使用JoinColumns注释而不是JoinColumn

@OneToOne(fetch = FetchType.LAZY)
@JoinColumns({
    @JoinColumn(name = "ACTVID", referencedColumnName = "ACTVID"),
    @JoinColumn(name = "ACTVATID", referencedColumnName = "ACTVATID")
})
private AtLinkData atLinkData;  

AtData实体的数据库表,您必须添加两个外键列ACTVIDACTVATID

<强>更新

如果您无法在Table 2中添加新列,请在mappedBy实体使用AtData属性,而不是AtLinkData。请尝试以下。

AtLinkData.java

@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ACT_AT_ID")
private AtData atData;

AtData.java

@OneToOne(fetch = FetchType.LAZY, mappedBy="atData")
private AtLinkData atLinkData;

答案 1 :(得分:0)

以下是我解决它的方法:

AtLinkData.java

@Id
@GeneratedValue(generator = "foreignGenerator")
@org.hibernate.annotations.GenericGenerator(name = "foreignGenerator", strategy = "foreign", parameters = @Parameter(name = "property", value = "atData"))
@Column(name = "ACT_AT_ID")
private long actvAtId;

@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ACT_AT_ID",insertable=false,updatable=false)
private AtData atData;
// getters, setters

AtData.java

@OneToOne(fetch = FetchType.LAZY, mappedBy="atData")
private AtLinkData atLinkData;

感谢@CycDemo的帮助。