How to create a business rule by JPA?

Asked

Viewed 227 times

1

I need to implement a business rule that ensures that the same employee represented by the table Employee cannot be added more than once to the same project represented by the table Project. Let me give 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 a save action for example below it generates an exception error;

EMP_PROJ (table)
EMP_ID  PROJ_ID
1         3

I can realize 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 project the system allowed and did not generate any exceptions despite creating a validation with Size.

How do I fix it?

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, launches the Exception and not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.