One-to-One Unidirectional Relationship
Learn how to model a unidirectional 1-1 relationship.
To model a one-to-one relationship, consider the scenario where a player has a profile that stores his details. We have a player table which stores the basic information about the player like id and name and a player_profile table which stores the additional details like the social media accounts of the players. There is a one-to-one relationship between player and player-profile tables, and in this lesson, we will model it as a one-way/ unidirectional relationship.
To keep the code organized, create a new package in io.datajek.databaserelationships
. We will call it onetoone
. Copy the DatabaseRelationshipsApplication.java
file from the main package to the onetoone
package.
Creating entities
Create a Player
class and mark it as an entity using @Entity
annotation. We will only create id and player name fields at the moment to keep this example simple.
Since Id
is the primary key, we will mark it with @Id
annotation and let Hibernate generate values for this column using the @GeneratedValue
annotation and a GenerationType
of IDENTITY
. Hibernate requires a default constructor. We will also create an overloaded constructor to create the object using fields, getters and setters for the fields, and a toString()
method.
@Entitypublic class Player {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private int Id;private String name;//constructorspublic Player( ) {}public Player(String name) {super();this.name = name;}//getters and setterspublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Player [id=" + id + ", name=" + name + "]";}}
Next, we will create the PlayerProfile
class in the onetoone
package to hold miscellaneous information about a player and also mark it as an entity. For now, this class will only store the player’s Twitter account handle.
@Entitypublic class PlayerProfile {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private int Id;private String twitter;//constructor//getters and setters//toString method}
We will mark the primary key with @Id
annotation and generate the constructors, getters, setters and ToString()
method as we did for the Player
class. The full code of the PlayerProfile
class can be seen from the executable code widget.
Running the application now will create two tables, player and player_profile, with no relationship defined between them. You can confirm this by visiting the H2 console at http://localhost:8080/h2-console
(using jdbc:h2:mem:testdb
as the connection URL).
One-to-One relationship
In SQL, we represent relationships using primary key and foreign key. Foreign keys are used to link tables together. A foreign key is a field in one table that refers to the primary key in another table. We will see how the same can be ...