Java 指定单向@OneToOne JPA映射的所有者
我在Java 指定单向@OneToOne JPA映射的所有者,java,hibernate,jpa,Java,Hibernate,Jpa,我在客户和发货地址之间有一对一的关系。我想确保如果删除了客户,那么发货地址也会被删除,因此我想将客户的密钥存储在发货地址表中。我只需要从客户导航到地址,即关系不需要是双向的 根据,关系应如下所示映射: @Entity public class Customer{ @OneToOne private ShippingAddress shippingAddress; } 但是,这将导致配送地址的密钥存储在客户中。我的反对意见是,这将允许某人在发货地址中插入一行,而无需将其与客户关
客户
和发货地址
之间有一对一的关系。我想确保如果删除了客户
,那么发货地址
也会被删除,因此我想将客户
的密钥存储在发货地址
表中。我只需要从客户导航到地址,即关系不需要是双向的
根据,关系应如下所示映射:
@Entity
public class Customer{
@OneToOne
private ShippingAddress shippingAddress;
}
但是,这将导致配送地址
的密钥存储在客户
中。我的反对意见是,这将允许某人在发货地址
中插入一行,而无需将其与客户
关联。类似地,它将允许某人在customer
中删除一行,而无需删除关联的地址
是否可以创建单向一对一映射,其中
- 您可以从父级(客户)导航到子级(发货地址)
- 父表的键存储在子表中
@Entity
public class Customer {
@Id
private long id;
@OneToOne(mappedBy="customer")
private ShippingAddress shippingAddress;
//...
}
@Entity
public class ShippingAddress {
@Id
private long id;
@OneToOne
@JoinColumn(name = "customer_id", referencedColumnName = "id")
private Customer customer;
//...
}
试试这个:
@Entity
public class Customer {
@Id
private long id;
@OneToOne(mappedBy="customer")
private ShippingAddress shippingAddress;
//...
}
@Entity
public class ShippingAddress {
@Id
private long id;
@OneToOne
@JoinColumn(name = "customer_id", referencedColumnName = "id")
private Customer customer;
//...
}
当然是。。检查
@OneToOne
注释的mappedBy属性(在您的示例中,将@OneToOne(mappedBy=“shippingAddress”
放在客户类中)顺便说一句:您应该指定一个客户@Id
字段also@Repoker我只包含了与my.questiontrue相关的JPA类元素,但是JPA需要一个带注释的@Id
字段来执行FK连接。您正在使用hibernate或其他方法生成架构,当然是..检查@OneToOne
注释(在您的示例中,将@OneToOne(mappedBy=“shippingAddress”
放在客户类中)顺便说一句:您应该指定一个客户@Id
字段also@Repoker我只包含了与我的.questiontrue相关的JPA类元素,但是JPA需要一个带注释的@Id
字段来执行FK join。您正在使用hibernate或其他方式生成架构。感谢您的编辑,我键入时很匆忙示例代码感谢您的编辑,我在键入示例代码时很匆忙