新表中的JPA ManyToOne [英] JPA ManyToOne in a new table
问题描述
我有下表: 标记,员工,位置. 员工和位置可以具有更多标签.我认为最好为这些关系创建新表:employee_tag和location_tag.
I have got the following tables: Tag, Employee, Location. Employee and Location can have more tags. I think it's best to create new tables for these relations so: employee_tag and location_tag.
如何使用JPA做到这一点?现在我明白了: 员工类别:
How do I do this using JPA? Right now I got this: Employee class:
@OneToMany()
@JoinTable(name="employee_tag", joinColumns={
@JoinColumn(name="ID_employee", referencedColumnName="ID")
}, inverseJoinColumns={
@JoinColumn(name="ID_tag", referencedColumnName="ID")
})
private Collection<Tag> tags;
标记类:
@ManyToOne()
private Employee employee;
它将创建一个名为employee_tag的新表,但tag仍具有一列employee_ID.如何将标签链接到该表?
It creates a new table named employee_tag but tag still has a column employee_ID. How do I link the tag to this table?
推荐答案
如果您需要单向一对多关联,则不必将雇员关联放在标记类中,而必须在员工班.
If you need a unidirectional one-to-many association, you have not to put the employee association in the tag class, you have to declare the association in the Employee class.
@Entity
public class Employee {
@OneToMany()
@JoinTable(name="employee_tag", joinColumns={
@JoinColumn(name="ID_employee", referencedColumnName="ID")
}, inverseJoinColumns={
@JoinColumn(name="ID_tag", referencedColumnName="ID")
})
public Collection<Tag> tags;
...
}
@Entity
public class Tag {
...
}
否则,您可以如下进行双向关联:
Otherwise you can do bidirectional association as below:
@Entity
public class Employee {
@OneToMany(mappedBy="troop")
public Collection<Tag> tags;
...
}
@Entity
public class Tag {
@ManyToOne
@JoinColumn(name="employee_fk")
public Employee employee;
...
}
看看休眠注释文档
这篇关于新表中的JPA ManyToOne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!