knowledge
knowledge

Reputation: 1025

JPA, Map entity Person which contains class of type Name

I have an entity Person which consists of a name Attribute

@Entity
public class Person {
      // ...
      //@Transient 
       private Name name;
      // ...
}

I dont want to store "name" in an extra table... I mark name as transient so it is not stored in the underlying database.

What I want is to map the attribute "name" to columns "first_name" and "last_name" in the database.

For example I can create a person like new Person(new Name("John","Doe"));

How can I achieve a mapping that the underlying table contains two additional columns first_name and last_name and the contents are the strings which I get from the name attribute?

The table, based on the person entity should look like

id|first_name|last_name 1 |John | Doe 2 |Jane | Doe

Upvotes: 0

Views: 107

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36223

You can use embeddables:

@Embeddable
public class Name {

    private String firstName;
    private String lastName;

    // getters and setters
}

And then use it like.

@Entity
public class Person {
      // ...
      private Name name;
      // ...
}

Read more about embeddables in the Hibernate documentation: https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#embeddables

Upvotes: 1

Related Questions