Skip to main content

How to create a Composite Key in Hibernate

Points To Remember

  • You need to create an Embedded Object to create a composite key in Hibernate.
  • You can create use an Embeddable Object as an EmbeddedId in class to make it a composite key.

Create a Composite Key in Hibernate

Suppose we have three classes User, Role and UserRole. In class UserRole we want to have a composite id that will include userId and roleId. Then we will first create an embedded object and then using this we will create a composite key.

Let us first create an Embeddable object and
User.java
package com.ekiras.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

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

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

@Column(name="email")
private String email;

@Column(name="password")
private String password;

// GETTERS and SETTERS
}

Role.java
package com.ekiras.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="role")
public class Role {

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

@Column(name="authority")
private String authority;

// GETTERS and SETTERS

}


UserRoleEmbed.java
package com.ekiras.embeddeble;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class UserRoleEmbed implements Serializable {

private static final long serialVersionUID = 1L;

@Column(name="user_id")
private Long userId;

@Column(name="role_id")
private Long roleId;

// GETTERS and SETTERS

}


UserRole.java
package com.ekiras.domain;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;

import com.ekiras.ekjam.embeddeble.UserRoleEmbed;

@Entity
@Table(name="user_role")
public class UserRole {

@EmbeddedId
private UserRoleEmbed userRole;

// GETTERS and SETTERS
}

So this will create the Composite key for class UserRole that we wanted and it will map key={userId, roleId}



The above image shows the database schema that the above code snippets created.

Comments