如何使一个复合主键

如何使一个复合主键

本文介绍了如何使一个复合主键(Java持久性注释)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让这个表user_roles两列(用户ID,角色ID)定义为一个复合主键。应该很容易,只是想不起/找到。

How to make it so that the table user_roles defines the two columns (userID, roleID) as a composite primary key. should be easy, just can't remember/find.

用户实体:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles")
public List<RoleDAO> getRoles() {
    return roles;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getUserID() {
    return userID;
}

角色实体:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles")
public List<UserDAO> getUsers() {
    return users;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getRoleID() {
    return roleID;
}

感谢您。

**更多资讯

因此​​,有一个第三个表 user_roles (由上面自动生成),这需要用户ID 用户实体和角色ID 角色实体。现在我需要在生成的表这两列( user_roles )是一个复合主键。

So there is a third table user_roles (auto generated by above) that takes userID from user entity and roleID from roles entity. Now I need those two columns in the generated table (user_roles) to be a composite primary key.

推荐答案

您已经有一些很好的答案,这里就怎么做完全一样,你问..

You've already had a few good answers here on how to do exactly as you ask..

有关引用让我提建议的方式做到这一点在Hibernate中,而不是,这是使用代理键作为主键,并标记业务键为NaturalId的:

For reference let me just mention the recommended way to do this in Hibernate instead, which is to use a surrogate key as primary key, and to mark business keys as NaturalId's:

虽然我们推荐使用
  代理键作为主键,你
  应尽量找出自然键
  为所有的实体。一个自然的关键是
  属性或属性的组合
  这是唯一的,非空。它是
  也不可改变的。地图的属性
  里面的关键自然
   元件。 Hibernate会
  生成必须的唯一密钥,
  空约束,并作为
  因此,你的映射会更加
  自文档。

建议您实现
  equals()和哈希code()比较
  实体的自然键属性。

It is recommended that you implement equals() and hashCode() to compare the natural key properties of the entity.

在code,使用注释,这将是这个样子:

In code, using annotations, this would look something like this:

@Entity
public class UserRole {
  @Id
  @GeneratedValue
  private long id;

  @NaturalId
  private User user;
  @NaturalId
  private Role role;
}

使用此会为你节省很多头痛的道路,因为你会发现,当你频繁地引用/映射组成的主键。

Using this will save you a lot of headaches down the road, as you'll find out when you frequently have to reference / map the composed primary key.

我发现这个硬盘的方式,而在刚刚结束的放弃了对战斗和Hibernate转而决定顺其自然。我完全理解,这可能无法在你的情况下,你可能会处理旧软件或依赖关系,但我只是想提以供将来参考。 (如果你不能用它也许别人可以的!)

I found this out the hard way, and in the end just gave up fighting against Hibernate and instead decided to go with the flow. I fully understand that this might not be possible in your case, as you might be dealing with legacy software or dependencies, but I just wanted to mention it for future reference. (if you can't use it maybe someone else can!)

这篇关于如何使一个复合主键(Java持久性注释)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:23