I have a many to many relationship like below.
@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EMP_ID")
private int id;
private String firstName;
private String lastName;
@JoinTable(name = "employee_project_mapping", joinColumns = @JoinColumn(name = "EMPLOYEE_ID", referencedColumnName = "EMP_ID"), inverseJoinColumns = @JoinColumn(name = "PROJECT_ID", referencedColumnName = "PJT_ID"))
@JsonManagedReference
@ManyToMany(cascade = CascadeType.ALL)
Set<Project> projects = new HashSet<Project>();
.....
.....
}
@Entity
@Table(name = "projects")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PJT_ID")
private int projectId;
private String projectName;
private int teamSize;
@ManyToMany(mappedBy = "projects")
@JsonBackReference
private Set<Employee> emps = new HashSet<Employee>();
.....
.....
}
@Entity
@Table(name = "employee_project_mapping")
public class EmployeeProjectMapping {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "EMP_PJT_ID")
private Integer empPjtId;
@Column(name = "PROJECT_ID")
private Integer projectId;
@Column(name = "EMPLOYEE_ID")
private Integer emploeeId;
.....
.....
}
But when I am trying to insert an employee object with set of projects, it is failing to create auto generated id for the column EMP_PJT_ID (this is an id to the mapping table record). Can't I add an auto generated id for mapping table using jpa?
Error trace
Hibernate: insert into employees (emp_id, first_name, last_name) values (null, ?, ?)
Hibernate: insert into employee_project_mapping (employee_id, project_id) values (?, ?)
2021-04-22 23:34:25.973 ERROR 24126 --- [nio-8080-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : NULL not allowed for column "EMP_PJT_ID"; SQL statement:
insert into employee_project_mapping (employee_id, project_id) values (?, ?) [23502-200]
2021-04-22 23:34:25.975 ERROR 24126 --- [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column "EMP_PJT_ID"; SQL statement:
insert into employee_project_mapping (employee_id, project_id) values (?, ?) [23502-200]