I have a situation where I want to retrieve data, but before it is returned I want to change it without saving/persisting.
Here is my rest controller:
@RestController
@RequestMapping("api/drawing-releases")
@CrossOrigin("*")
public class DrawingReleaseRestController {
@Autowired
private DrawingReleaseService service;
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
@JsonView(View.DrawingReleaseView.class)
public ResponseEntity<DrawingRelease> getWithId(@PathVariable int id) throws EntityNotFoundException {
return new ResponseEntity<>(service.getByID(id),HttpStatus.OK);
}
}
Here is the service implementation:
@Service
public class DrawingReleaseServiceImpl extends DrawingFunctions implements DrawingReleaseService {
/**
* Logging Manager
*/
private static final Logger LOGGER=LogManager.getLogger();
@Autowired
private DrawingReleaseRepository repository;
@Override
public DrawingRelease getByID(int id) throws EntityNotFoundException {
Optional<DrawingRelease> opt = repository.findById(id);
...
// manipulate the data here
...
return opt.get();
}
}
Intitially I had the @Transactional
annotation on the service. By removing that and not having it on the getByID
method, I was first thinking that the session would open and close with the repository as indicated by the answer here.
That did not work, and I saw in the comments that "the session lasts for the entire duration of HTTP request processing." So, in the service I added
@Autowired
private EntityManager em;
and then in the getByID
method I added
em.close();
before I made any changes. However, any changes I make are still being persisted.
Is there any way that I can make unsaved changes in my service layer? I suppose I could create some POJOs that mirror the entities (but aren't entities) and then copy the data and return those objects, but it doesn't seem like I should have to do something like that.