Question: package Lab.Service; import Lab.Exceptions.InvalidTonnageException; import Lab.Model.Ship; import Lab.Repository.ShipRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; / * * * TODO: Using the
package Lab.Service;
import Lab.Exceptions.InvalidTonnageException;
import Lab.Model.Ship;
import Lab.Repository.ShipRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
TODO: Using the Transactional annotation, cause the methods of this Service class to roll back the current
database transaction when the InvalidTonnageException is thrown. This will wrap all
methods in this class inside of a database transaction, which will prevent incomplete updates in the event of an
exception being thrown. It should be assigned to rollback the transaction for some exception, hence the rollbackFor.
You can test this by attempting to persist a list of ships where some ship in the JSON has a negative tonnage, then
attempting to get all ships. No ships should be persisted if any ship in the array has a negative or zero
tonnage we're left to assume some form of unwanted user error in that case.
@Service
public class ShipService
ShipRepository shipRepository;
@Autowired
public ShipServiceShipRepository shipRepository
this.shipRepository shipRepository;
this is a bad way to save a list to the repository as you can just use the saveAll method provided the table
has a CHECK constraint to check tonnage, but this gets the point across for the importance of @Transactional
@param ships transient ship entities
@throws InvalidTonnageException ships can not have negative tonnage theyd sink
public List addListShipsList ships throws InvalidTonnageException
List persistedShips new ArrayList;
forint i ; i ships.size; i
ifshipsgetigetTonnage
throw new InvalidTonnageException;
persistedShips.addshipRepositorysaveshipsgeti;
return persistedShips;
@return all ship entities
public List getAllShips
return shipRepository.findAll;
@return ship entity by id
public Ship getShipByIdlong id
return shipRepository.findByIdidget;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
