Search code examples
javajpapersistenceentity

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. 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.


Solution

  • This is possible and JPA basics. But you have to define the associations between entities in your entity classes.

    I recommend reading a good tutorial on this topic, e.g. the Java EE6 tutorial.