我有hibernate实体,名为provider,如下所示,
@Entity
@Table
public class Provider {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column
private String name;
@Column
private String type;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
它包含基于类型的不同类型的提供程序
在这里,我需要在学生提供者和课程提供者之间建立多对多的关系。为此我创建了一个新实体,如下所示,
public class StudentToCourseProvider {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne
@JoinColumn(name = "student_id")
private Provider studentProvider;
@ManyToOne
@JoinColumn(name = "course_id")
private List<Provider> courseProvider;
public Provider getStudentProvider() {
return studentProvider;
}
public void setClinicalProvider(Provider studentProvider) {
this.studentProvider = studentProvider;
}
public Provider getCourseProvider() {
return courseProvider;
}
public void setCourseProvider(Provider courseProvider) {
this.courseProvider = courseProvider;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
我需要创建没有id(主键)的 StudentToCourseProvider 实体。如何做?
答案 0 :(得分:0)
一种可能的方法是使用继承:
@Entity
@Inheritence(strategy = InheritenceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Provider { ... }
@Entity
@Discriminator("st")
public class StudentProvider extends Provider {
@ManyToMany
private List<CourseProvider> courseProviders = ...;
}
@Entity
@Discriminator("cp")
public class CourseProvider extends Provider {
@ManyToMany(mappedBy = "courseProviders")
private List<StudentProvider> studentProviders = ...;
}
在这种情况下,您从type
类中删除Provider
字段并将其转换为鉴别符。如果您有预定义的可能类型集,则此方法有效。
或者,您可以在Provider
中创建单个多对多关系,并在代码中强制执行约束。如果您有不确定的可能类型集,这将有效。请注意,在这种情况下,您应该注意关系的直接性。