我有两个具有多对多关系的实体。关系表也是映射的广告实体。它具有id列和IDENTITY策略。
@Entity
@Table(name = "Employee")
public class Employee {
// ...
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Employee_Project",
joinColumns = { @JoinColumn(name = "employee_id") },
inverseJoinColumns = { @JoinColumn(name = "project_id") }
)
Set<Project> projects = new HashSet<>();
// standard constructor/getters/setters
}
@Entity
@Table(name = "Project")
public class Project {
// ...
@ManyToMany(mappedBy = "projects")
private Set<Employee> employees = new HashSet<>();
// standard constructors/getters/setters
}
@Table
public class EmployeeProject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EmployeeProjectId", nullable = false)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "EmployeeId", nullable = false)
private Employee employee;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "ProjectId", nullable = false)
private Project project;
}
如果Employee实体没有@JoinTable映射生成SQL如下所示:
create table EmployeeProject (EmployeeProjectId integer generated by default as identity
然而,在员工生成中添加@JoinTable映射后,SQL更改为:
create table EmployeeProject (EmployeeProjectId integer not null
如何强制hibernate始终生成SQL的第一个版本?
你不能,也不应该。如果你想为EmployeeProject
实体建模,那么你也应该使用它,即将多对多关联映射为两个一对多关联:
@Entity
@Table(name = "Employee")
public class Employee {
// ...
@ManyToMany(mappedBy = "employee", cascade = { CascadeType.ALL })
Set<EmployeeProject> projects = new HashSet<>();
// standard constructor/getters/setters
}
@Entity
@Table(name = "Project")
public class Project {
// ...
@ManyToMany(mappedBy = "project")
private Set<EmployeeProject> employees = new HashSet<>();
// standard constructors/getters/setters
}