Sunday, 14 February 2021

Hibernate relationship one to one

 Types of relations:

1. One-To-One

2. One-To-Many

3. Many-To-One

4. Many-To-Many


1. One-To-One


one to one relationship can be of two types

a) Mandatory

b) Optional 


a) Mandatory


a.1) Using foreign key



Into above entity diagram as we can see that here we have two tables

1. Users

2. Address

If one user have only one address then we can use one to one relationship here.

For this we define address_id  column into users table.



import javax.persistence.*;

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

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;
	
	@Column(name = "user_name")
	private String userName;
	
	@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(name="address_id", referencedColumnName = "id")
	private AddressEntity addressEntity;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public AddressEntity getAddressEntity() {
		return addressEntity;
	}

	public void setAddressEntity(AddressEntity addressEntity) {
		this.addressEntity = addressEntity;
	}
	
	
	
}



import javax.persistence.*;

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

	private long id;
	
	@OneToOne(mappedBy="addressEntity")
	private UserEntity userEntity;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public UserEntity getUserEntity() {
		return userEntity;
	}

	public void setUserEntity(UserEntity userEntity) {
		this.userEntity = userEntity;
	}
	
	
}