When programming multi-tier application it seems to be best practice to pass only object ids to transactional service methods. But I would rather like to pass actual JPA objects. Unlike in the question Is domain model object passing between layers overhead? some colleagues fear that a) object could belong to another/no transaction if and thus cause problems when modified inside the service method and b) objects could cause problems when modified after invoking such a service method from the UI component because the transaction is already committed.
Expressed in code I would rather like to have
@Named public class MyServiceImpl
{
...
@Transactional
public BigDecimal calculate(ObjectOne objectOne, ObjectTwo objectTwo)
{
...
}
}
instead of
@Named public class MyServiceImpl
{
...
@Transactional
public BigDecimal calculate(long objectOneId, long objectTwoId)
{
ObjectOne objectOne = objectOneService.find(objectOneId);
ObjectTwo objectTwo = objectTwoService.find(objectTwoId);
...
}
}
So is there a technique where the transaction manager (spring) cares for the objects properly? Or do you recommend to use JPA merge or anything else explicitly to handle direct object references properly? Or do you discourage passing objects instead of IDs as well?
Especially explanations with links to official or well-known sources would be helpful, obviously.