简体   繁体   English

可以使用实体字段保留JPA实体吗?

[英]Persisting JPA entities with entity fields possible?

If I have an entity such as the following: 如果我有一个如下的实体:

@Entity
public class Customer {
    private Address address;
}

And the Address is also an entity: 地址也是一个实体:

@Entity
public class Address {...}

Does persisting the Customer in turn persist its contained Address? 是否坚持客户反过来坚持其包含的地址? Or is this not possible at all? 或者这根本不可能? The idea was basically to have a main entity that consists of its fields, some of which are entities themselves that will be stored in individual tables. 这个想法基本上是有一个由其字段组成的主要实体,其中一些实体本身将存储在各个表中。 Some of the fields of Customer are unique in that I also would like a Customer table for that data. Customer的某些字段是唯一的,因为我还希望获得该数据的Customer表。 Unless I'm just missing it, I haven't been able to find this answer. 除非我错过了,否则我找不到这个答案。 This was something I was just curious about and I'm not currently on a machine where I can try it, so I wanted to ask first. 这是我只是好奇的事情,我目前不在我可以试用的机器上,所以我想先问一下。

Thanks in advance. 提前致谢。

This is possible and JPA basics. 这是可能的和JPA基础。 But you have to define the associations between entities in your entity classes. 但是您必须定义实体类中实体之间的关联。

I recommend reading a good tutorial on this topic, eg the Java EE6 tutorial . 我建议阅读关于这个主题的好教程,例如Java EE6教程

You have 2 options depending on your domain model: 您有2个选项,具体取决于您的域模型:

  • removing the @Entity from address and annotate it with @Embeddable 从地址中删除@Entity并使用@Embeddable注释它

  • mapping the Address in the Person with: @OneToOne(cascade = {CascadeType.PERSIST}) 使用以下内容映射Person中的地址:@OneToOne(cascade = {CascadeType.PERSIST})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM