Thursday 8 December 2022

Using Composite Key in Hibernate With Spring Boot

 This post contains an example showing how we can use a composite key in hibernate with spring.


We have an employee that has multiple tasks. I am not posting the DB, the reason is that I have turned on the ddl-auto to true. If you need to automatically update the DB when spring loads the entities, add the following property to the application.properties file.

spring.jpa.hibernate.ddl-auto=update

Coming back to the code part. Here is an Employee class.

import com.fasterxml.jackson.annotation.JsonManagedReference;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import lombok.Data;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
@Entity
public class Employee implements Serializable {
@Id
private long employeeId;
private String name;
private String dept;
@JsonManagedReference
@OneToMany(mappedBy = "employee")
List<Task> taskList;

}
and the following section contains the Task class


import com.fasterxml.jackson.annotation.JsonBackReference;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class Task implements Serializable {
@EmbeddedId
private CompositeTaskId taskId;

@JsonBackReference
@MapsId("employeeKey")
@ManyToOne
private Employee employee;

private String taskName;
private Date date;
}
and CompositeTaskId

import java.io.Serializable;
import javax.persistence.Embeddable;
import lombok.Data;
import lombok.RequiredArgsConstructor;

@Data
@RequiredArgsConstructor
@Embeddable
public class CompositeTaskId implements Serializable {
private long employeeKey;
private long taskId;

}
Running the code with controllers will create DB  given table and composite key.


P.S. I have re-used code from some example online as well but don't remember the reference link.