在使用序列生成器的同一对象中定义主键和外键

时间:2013-12-02 14:27:36

标签: java jpa sequence

我创建了一个Address对象,它有一个由序列生成的ID(AddressPK)。地址对象还通过客户端对象的ID(ClientPK)具有Client对象的外键。 ClientPK也通过序列生成。但是,当我尝试将耳朵部署到Web逻辑服务器时,它抱怨说实体只能存在一个生成的元素。该课程片段如下。任何人都可以帮助如何使用除了对象主键之外还使用序列生成器的对象来定义外键?

public class Address implements Serializable{
@EmbeddedId
private AddressPK id;

@Embedded
private ClientPK clientId;

...
}

@Embeddable
public class AddressPK implements Serializable {
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="RoidSequenceGenerator")
@SequenceGenerator(name="RoidSequenceGenerator",sequenceName="roid_sequence", allocationSize=1)    
@Column(name = "a_roid")
private long value;
...
}

@Embeddable
public class ClientPK implements Serializable {
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="RoidSequenceGenerator")
@SequenceGenerator(name="RoidSequenceGenerator",sequenceName="roid_sequence", allocationSize=1)
@Column(name = "c_roid")
private long value;
...
}

1 个答案:

答案 0 :(得分:0)

我认为您不明白什么是主键以及与外键的区别。可以为每个数据库实体生成主键(PK)。 JPA中有一个限制,即生成的值必须只有一个。另一方面,外键(FK)是指向另一个实体的PK的链接。因此,您需要使用生成的PK创建另一个实体,并使用OneToMany,ManyToMany或其他类型的关联链接到它。例如:

@TableGenerator(name = "entities_id_generator", table = "SEQUENCE",                
pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = 
"ENTITY_SEQ", initialValue = 0, allocationSize = 1)
public class DBObject1 implements Serializable {
@Id
@GeneratedValue(generator = "entities_id_generator", strategy = GenerationType.TABLE)
private Long id;
@ManyToOne
@JoinColumn(name = "source_id")
private DBObject2 source;
}

@TableGenerator(name = "entities_id_generator", table = "SEQUENCE",                 
pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = 
"ENTITY_SEQ", initialValue = 0, allocationSize = 1)
public class DBObject2 implements Serializable {
@Id
@GeneratedValue(generator = "entities_id_generator", strategy = GenerationType.TABLE)
private Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "source")
private List<DBObject1> objects;
}

在上面的示例中,实体DBObject1的虚拟FK将存储在列source_id中。它是虚拟的,因为数据库表中不会有任何物理FK。但是,如果你问,JPA会链接这些对象。