如何使用 JPA 注释创建连接表? [英] How to create join table with JPA annotations?
问题描述
我需要使用 JPA
注释在我的数据库中创建一个连接表,因此结果将是:
I need to create a join table in my database using JPA
annotations so the result will be this:
到目前为止,我只实现了 2 个实体:
So far I just implemented 2 entities:
@Entity
@Table(name="USERS", schema="ADMIN")
public class User implements Serializable {
private static final long serialVersionUID = -1244856316278032177L;
@Id
@Column(nullable = false)
private String userid;
@Column(nullable = false)
private String password;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@Entity
@Table(name="GROUPS", schema="ADMIN")
public class Group implements Serializable {
private static final long serialVersionUID = -7274308564659753174L;
@Id
@Column(nullable = false)
private String groupid;
public String getGroupid() {
return groupid;
}
public void setGroupid(String groupid) {
this.groupid = groupid;
}
}
我应该创建另一个名为 USER_GROUP
的实体,还是我可以添加一些注释,以便在我从实体 (ORM) 运行创建表时自动创建连接表?
Should i create another entity called USER_GROUP
or i can just add some annotations, so the join table will be created automatically when i run create tables from entities(ORM)?
我应该如何注释我的实体以实现与图像中相同的效果?
How should i annotate my entities to achieve the same as in the image?
推荐答案
您绝对不应该创建 User_Group 实体,因为它更多是底层数据库表示而不是面向对象的表示.
You definitely shouldn't create User_Group entity as it's more the underlying database representation than the object oriented one.
你可以通过定义类似的东西来实现连接表:
You can achieve the join table by defining something like:
@Entity
@Table(name="USERS", schema="ADMIN")
public class User implements Serializable {
//...
@ManyToOne
@JoinTable(name="USER_GROUP")
Group group;
<小时>
@Entity
@Table(name="GROUPS", schema="ADMIN")
public class Group implements Serializable {
//...
@OneToMany(mappedBy="group")
Set<User> users;
如果您想明确设置列的名称,您可以使用@JoinColumn 元素,如下所示:
If you want to explicitly set the names of the columns you could use @JoinColumn elements as shown below:
@ManyToOne
@JoinTable(name="USER_GROUP",
joinColumns = @JoinColumn(name = "userid",
referencedColumnName = "userid"),
inverseJoinColumns = @JoinColumn(name = "groupid",
referencedColumnName = "groupid"))
Group group;
这篇关于如何使用 JPA 注释创建连接表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!