How to implement Service Layer with Spring?

3

Does anyone know of any tutorial, examples ... any source to learn how to implement service layer?

    
asked by anonymous 21.12.2015 / 15:48

1 answer

3

The service layer is where you will have all your business rules before persistence and of course where you will control the database transaction.

//declare aqui a anotação service
@Service
public class MyService {

      ...
}

For transaction control use @Transactional (readOnly = true) by default spring already sets the commit to commit only when all goes well with your method.

You can change this with:

 @Transactional(propagation=Propagation.REQUIRED,readOnly=false) 
    public void save(ProductTech product) { 
        currentSession().save(product); 
        System.out.println(“product saved with sucess”); 
    } 

PROPAGATION_MANDATORY : Requires the use of a transaction, if there is no current transaction, an exception is thrown.

PROPAGATION_NESTED : Runs within a nested transaction if a current transaction exists.

PROPAGATION_NEVER : Prevents use of a transaction. If an existing transaction exists, an exception is thrown.

PROPAGATION_NOT_SUPPORTED : Do not use the current transaction. This is always executed without any transaction.

PROPAGATION_REQUIRED : Uses the current transaction if it exists, if it does not exist create a new transaction.

PROPAGATION_REQUIRES_NEW : Create a new transaction, if a current already exists, suspend it.

PROPAGATION_SUPPORTS : Uses the current transaction if it exists, otherwise it runs without transaction.

Ready after that, just inject your Service into your Controller

    
21.12.2015 / 16:07