I need to implement a business rule that ensures that the same employee represented by the Employee table can not be added more than once to the same project represented by the Project table. Let me give you an example;
Let's assume we have the following records
EMPLOYEE (table)
ID NAME
1 Bob
2 Sarah
PROJECT (table)
ID NAME
1 GIS
2 SIG
The system identifies the following actions when saving a record
EMP_PROJ (table)
EMP_ID PROJ_ID
1 1
1 2
2 1
The business rule is when there is an save action for example below it generates an exception error;
EMP_PROJ (table)
EMP_ID PROJ_ID
1 3
I can perform the exception through JPA mapping, see the mapping;
Project
@Entity
@Table(name = "project")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotNull
@Size(min = 2, max = 300)
private String name;
Emp_Proj
@Entity
@Table(name = "emp_proj")
public class Emp_Proj {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long emp_id;
private Long proj_id;
Employee
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(min = 2, max = 300)
private String name;
@NotNull
private BigDecimal salary;
@Size(min = 2, message = "Selecione pelo menos dois projetos")
@ManyToMany
@JoinTable(name = "Emp_Proj", joinColumns = @JoinColumn(name = "emp_id")
, inverseJoinColumns = @JoinColumn(name = "proj_id"))
What happened was that when trying to insert an employee into three projects the system allowed and did not generate any exceptions even though you have created a validation with Size .
How do I resolve this?