Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create hibernate composite key using annotations

I am trying to use hibernate annotations to insert data to a MySQL database table which doesn't have a primary key defined.

However the fact is 2 fields of that table together are unique in the table.how can i achieve the same using hibernate annotation?.

here is my code..

 @Entity  @Table(name = "RolesMenuItems")     public class RolesMenuItems {         @Column(name = "RoleID")        private String roleID;         @Column(name = "MenuItemID")        private String menuItemID;   /*setter getter methods */  } 
like image 291
edaklij Avatar asked Dec 18 '12 15:12

edaklij


People also ask

How do you define a composite key in hibernate using annotations?

A composite primary key, also called a composite key, is a combination of two or more columns to form a primary key for a table. In JPA, we have two options to define the composite keys: the @IdClass and @EmbeddedId annotations.

Can we use composite keys in hibernate?

Use embeddable objects to join two primary keys into one composite key. Every JPA entity has a primary key, but some entities have more than one value as their primary key. In this case, you need to use a composite key. This Java tip introduces you to using composite keys in JPA and Hibernate.

What annotation is used for a composite primary key type?

The EmbeddedId and IdClass annotations are used to denote composite primary keys.


1 Answers

You can use @Embeddeble and @EmbeddedId to create a composite key and map it with your Entity. For example:

@Embeddable public class RolesMenu {     @Column(name = "RoleID")     private String roleID;      @Column(name = "MenuItemID")     private String menuItemID;      //getter, setter methods }   @Entity  @Table(name = "RolesMenuItems")  public class RolesMenuItems {       @EmbeddedId      private RolesMenu roleMenu;    /*setter getter methods */  } 

Then use RolesMenuItems in your Java code to persist entities in usual way.

Reference: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e535

Edit: To persist the entity:

RolesMenu roleMenu = new RolesMenu(); roleMenu.setRoleID(...); roleMenu.setMenuItemID(...);  RolesMenuItems roleItem = new RolesMenuItems(); roleItem.setRoleMenu( roleMenu );  em.persist(roleItem); 
like image 129
Viral Patel Avatar answered Sep 27 '22 18:09

Viral Patel