Reputation: 53
I am creating two tables using Spring boot and JPA:
Apartment table: id, name, address_id, website
Address table: id, street_num, street, city, .....
the address_id should be the foreign key and pointing to id in address table.
I couldn't get my code working. Here are my two Entity classes:
Apartment.java:
@Entity
public class Apartment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name = "address",
joinColumns = @JoinColumn(name = "apt_id"))
private Address address;
private String website;
//getters and setters
Address.java:
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Integer apt_id;
private String streetNum;
private String street;
private String city;
private String state;
private String zipCode;
//getters and setters
what I am getting is an extra column called address_id in address table....and missing address_id in apartment table....
Many Thanks!
Upvotes: 0
Views: 86
Reputation: 107
Hibernate one to one mapping with foreign key association
In this kind of association, a foreign key column is created in owner entity The join column is declared with the @JoinColumn annotation which looks like the @Column annotation. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join.
Replace Your Apartment Class with this:
@Entity
public class Apartment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "apt_id"))
private Address address;
private String website;
//getters and setters
Upvotes: 0