java复合主键注解,如何使一个复合主键(Java持久性注释)

这篇博客讨论了如何在Hibernate中为user_roles表设置由userID和roleID组成的复合主键。作者建议使用代理主键并标记业务键为NaturalId,以简化映射并提高代码可读性。虽然这可能不适用于所有情况,特别是处理遗留软件或依赖时,但这种做法有助于减少后续问题。
摘要由CSDN通过智能技术生成

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.

In user entity:

@ManyToMany(fetch = FetchType.LAZY)

@JoinTable(name = "user_roles")

public List getRoles() {

return roles;

}

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

public Integer getUserID() {

return userID;

}

In roles entity:

@ManyToMany(fetch = FetchType.LAZY)

@JoinTable(name = "user_roles")

public List getUsers() {

return users;

}

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

public Integer getRoleID() {

return roleID;

}

Thank you.

** MORE INFO

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..

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:

Although we recommend the use of

surrogate keys as primary keys, you

should try to identify natural keys

for all entities. A natural key is a

property or combination of properties

that is unique and non-null. It is

also immutable. Map the properties of

the natural key inside the

element. Hibernate will

generate the necessary unique key and

nullability constraints and, as a

result, your mapping will be more

self-documenting.

It is recommended that you implement

equals() and hashCode() to compare the

natural key properties of the entity.

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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值