How to create hibernate composite key using annotations
Asked Answered
A

1

27

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 */
 }
Alkalize answered 18/12, 2012 at 15:36 Comment(0)
E
63

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);
Eyra answered 18/12, 2012 at 15:45 Comment(5)
OK thank you..but how can i insert values for roleID and menuItemID..can you please tell me??Alkalize
Updated the answer. Pl have a look.Eyra
have any getter setter methods in RolesMenu class??Alkalize
how can i specifies column names for roleID,menuItemID?Alkalize
Can we generate the composite key using generation strategies? I mean roleID and menuItemID as Auto increment. I guess yes, we can do it.Slinkman

© 2022 - 2024 — McMap. All rights reserved.