hibernate one-to-one

hibernate one-to-one

Knowledge

https://www.baeldung.com/jpa-one-to-one

Screen Shot 2020-11-24 at 3.23.00 PM

address_id in users is the foreign key to address

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
//...

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;

// ... getters and setters
}

@Entity
@Table(name = "address")
public class Address {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
//...

@OneToOne(mappedBy = "address")
private User user;

//... getters and setters
}

Notes: whoever *owns* the foreign key column gets the *@JoinColumn* annotation.

Use Join table

One-to-one mappings can be of two types – Optional and Mandatory. For optional, 使用join table 较方便,不需要设置null .

Screen Shot 2020-11-24 at 3.25.00 PM
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

//...

@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name = "emp_workstation",
joinColumns =
{ @JoinColumn(name = "employee_id", referencedColumnName = "id") },
inverseJoinColumns =
{ @JoinColumn(name = "workstation_id", referencedColumnName = "id") })
private WorkStation workStation;

//... getters and setters
}

@Entity
@Table(name = "workstation")
public class WorkStation {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

//...

@OneToOne(mappedBy = "workStation")
private Employee employee;

//... getters and setters
}

[@*JoinTable*](http://docs.jboss.org/hibernate/jpa/2.2/api/javax/persistence/JoinTable.html) instructs Hibernate to employ the join table strategy while maintaining the relationship.

Also, Employee is the owner of this relationship as we chose to use the join table annotation on it.


Practice


CREATE TABLE CustomerProfile (
cp_id int AUTO_INCREMENT,
gender varchar(10),
phone varchar(20),
birthday date,
address varchar(50),
PRIMARY KEY (cp_id)
)ENGINE=INNODB;

CREATE TABLE Customer (
customer_id int AUTO_INCREMENT,
name varchar(20),
email varchar(20),
cp_id int NOT NULL,
PRIMARY KEY (customer_id),
FOREIGN KEY (cp_id) REFERENCES CustomerProfile(cp_id)
) ENGINE=INNODB;