[英]How to create a foreign key to columns of an ElementCollection in JPA?
Given the following class model:给定以下类模型:
package demo;
import java.util.Map;
import java.util.Set;
import javax.persistence.*;
@Embeddable
class Address {
String street;
}
@Embeddable
class AddressDetails {
byte[] photo;
}
@MappedSuperclass
abstract class User {
@Id Long id;
@ElementCollection(fetch = FetchType.EAGER) Set<Address> addresses;
@ElementCollection Map<Address, AddressDetails> addressDetails; // wanted: FK to addresses
}
@Entity
class Sub1 extends User {}
@Entity
class Sub2 extends User {}
I'm trying to tell JPA that addressDetails
references rows from addresses
.我试图告诉 JPA
addressDetails
引用来自addresses
行。 How can I do that?我怎样才能做到这一点?
This is the foreign key constraint that I'd like to convert to annotations :这是我想转换为注释的外键约束:
ALTER TABLE sub1_address_details
ADD CONSTRAINT FK_sub1_address_address_details
FOREIGN KEY (sub1_id, address_id)
REFERENCES sub1_addresses
ON DELETE CASCADE;
This is the foreign key constraint that Hibernate generates currently:这是Hibernate当前生成的外键约束:
alter table vblife_pv.sub1_addresses
add constraint FKdm58cvoq5gqndtlpr4t7auyct
foreign key (sub1_id)
references sub1
I tried to add我试着添加
@CollectionTable(joinColumns = {@JoinColumn(table = "addresses", referencedColumnName = "id")})
to addressDetails
, but this does not change Hibernate's DDL output.到
addressDetails
,但这不会改变 Hibernate 的 DDL 输出。
I'm using Hibernate 5.4.21.我正在使用 Hibernate 5.4.21。
If you really want that, you should probably use the following:如果你真的想要那个,你可能应该使用以下内容:
@Entity
@Table(name = "addresses")
public class UserAddress {
@EmbeddedId
UserAddressId id;
@ManyToOne(LAZY)
@JoinColumn(name = "address_id", insertable = false, updatable = false)
Address address;
@ManyToOne(LAZY)
@JoinColumn(name = "user_id", insertable = false, updatable = false)
User user;
@OneToOne(mappedBy = "userAddress")
AddressDetails details;
}
@Embeddable
public class UserAddressId {
int addressId;
int userId;
}
@Entity
@Table(name = "address_details")
public class AddressDetails {
@EmbeddedId
UserAddressId id;
@OneToOne
@JoinColumns({
@JoinColumn(name = "user_id", referencedColumn = "user_id", insertable = false, updatable = false),
@JoinColumn(name = "address_id", referencedColumn = "address_id", insertable = false, updatable = false)
})
UserAddress userAddress;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.