Gleyak
Gleyak

Reputation: 564

JPA OneToOne relation on the same SQL table

Given the client class

public class Client {

 private String firstName;
 private String lastName;
 private Address address;
  //..//
 }

and the Address Class

public class Address {

private int houseNumber;
private String streetName;
private String city;
private String state;
private String zipCode;
private String country;
//...//
}

I've created the address class since it is used in some other class and I didnt want to duplicate the code. Is there a way, using JPA, to explicitly have the Address information into my Client SQL table instead of creating an Address Table and use the primary key as link between the two?

Upvotes: 2

Views: 657

Answers (1)

JEY
JEY

Reputation: 7133

You don't need a OneToOne relationship you can use Embeddable type.

@Entity
public class Client {
    @Id
    private long id;
    private String firstName;
    private String lastName;
    @Embedded
    private Address address;
}

@Embeddable
public class Address {
    private int houseNumber;
    private String streetName;
    private String city;
    private String state;
    private String zipCode;
    private String country;
}

This way you map a table client with the following column:

first_name, last_name, house_number, street_name, city, state, zip_code, country

And you can reuse the Address on any other entity that has the same columns in their table.

Upvotes: 6

Related Questions