我有两个实体类Activity
和User
. 它们之间的关系是:
- 一个
Activity
可以有一个或多个User
- 一罐
User
属于一个或多个Activity
因此,为了实现这一点,我定义@ManyToMany
了它们之间的映射。下面是我的课:
Activity
:
@javax.persistence.Entity
@Table(name = "ACTIVITY")
public class Activity extends Entity {
@Transient
private static final long serialVersionUID = 4741665931936809028L;
private Set<User> users;
public Activity() {
super();
}
@ManyToMany(targetEntity = User.class, cascade = { CascadeType.ALL })
@JoinTable(name = "ACTIVITY_USER", joinColumns = @JoinColumn(name = "ID"), inverseJoinColumns = @JoinColumn(name = "ID"))
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
User
:
@javax.persistence.Entity
@Table(name = "USER")
public class User extends Entity {
@Transient
private static final long serialVersionUID = -112950002831333869L;
private Set<Activity> activities;
public User() {
super();
}
@ManyToMany(cascade = { CascadeType.ALL }, mappedBy = "users", targetEntity = Activity.class)
public Set<Activity> getActivities() {
return activities;
}
public void setActivities(Set<Activity> activities) {
this.activities = activities;
}
}
以上两个类都扩展了Entity
:
@MappedSuperclass
public class Entity implements Serializable {
@Transient
private static final long serialVersionUID = 7470288121057059283L;
private Long id;
public Entity() {
super();
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", updatable = false, nullable = false, unique = true)
public Long getId() {
return id;
}
@SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
public void setLastUpdateTimestamp(Date lastUpdateTimestamp) {
this.lastUpdateTimestamp = lastUpdateTimestamp;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
return prime * result + ((getId() == null) ? super.hashCode() : getId().hashCode());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!getClass().equals(HibernateProxyHelper.getClassWithoutInitializingProxy(obj))) {
return false;
}
final Entity other = (Entity) obj;
if (getId() != other.getId()) {
if (getId() == null) {
return false;
}
if (!getId().equals(other.getId())) {
return false;
}
}
return true;
}
}
现在从:
@JoinTable(name = "ACTIVITY_USER", joinColumns = @JoinColumn(name = "ID"), inverseJoinColumns = @JoinColumn(name = "ID"))
据我所知,of 的@JoinColumn
名称joinColumns
采用一个实体的 PK 的列名,而 of 的@JoinColumn
名称inverseJoinColumns
采用另一个实体的 PK 的列名。但在我的情况下,两个列名都是相同的,即ID
来自Entity
类。
我的问题是如何避免列名的这种冲突?任何建议都会对我很有帮助。