How to create a business rule by JPA?

1

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?

    
asked by anonymous 17.09.2018 / 21:11

1 answer

1

In your repository, if you are using Spring data JPA you can do the following:

    public interface ProjectRepository extends CrudRepository<Emp_Proj, Long> {
       @Query("SELECT COUNT(e) FROM Emp_Proj e WHERE e.emp_id=:id")
       Long numProjetosFuncionarios(@Param("id") Long id);
    }

Then with this return you treat your business rule, for example if the result is greater than 2, it throws the exception and not.

    
17.09.2018 / 22:23