Skip to main content

One to One mapping (shared primary key) in JPA with Spring Boot

Required Dependency

pom.xml

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.46</version>
</dependency>

application.properties

application.properties

spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.url=jdbc:mysql://localhost:3306/one_to_one_demo?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
logging.level.org.hibernate.SQL=DEBUG

Entity

ProductEntity.java

package in.tecmentor.entity;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="product_mst")
public class ProductEntity {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long productId;
	private String productBarcode;
	private String productName;
	private Double price;
	private Long quantity;
	private Boolean isActive;

	@OneToOne(fetch = FetchType.LAZY, mappedBy = "product", cascade = CascadeType.ALL)
	private ProductDetailsEntity productDetails;

	//Getters and setters are omitted for brevity
}

ProductDetailsEntity.java

package in.tecmentor.entity;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name="product_details_mst")
public class ProductDetailsEntity {

	@Id
	@GenericGenerator(name = "product-id-generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "product"))
	@GeneratedValue(generator = "product-id-generator")
	private Long proDetailId;
	private String brandName;
	private Long productRating;
	private String address;
	private String city;
	private String state;
	private String country;
	private String pin;

	@OneToOne(fetch = FetchType.LAZY)
	@PrimaryKeyJoinColumn
	private ProductEntity product;

	//Getters and setters are omitted for brevity
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Top