How to create hibernate composite key using annotations

雨燕双飞 提交于 2019-12-28 05:07:09

问题


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 */
 }

回答1:


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);


来源:https://stackoverflow.com/questions/13936340/how-to-create-hibernate-composite-key-using-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!