Hi,
I have a problem with a method that have to deal with entities in different object states. Let me explain it.
My application manages (simplified) organisations, devices and users. They are related as follows:
Code:
user 1 ----- 1 organisation 1 ---- n device
So one organisation has one user and n devices.
Our architecture looks (simplified again) like
Code:
GUI
Business Logic 1 (BL1)
Business Logic 2 (BL2)
Data Access Objects (DAO)
Domain Model
where a class is only allowed to call classes in the layer directly below its own layer (exclusions: GUI may access BL2 directly, Domain Model may be accessed from any layer).
In the BL2 we have a device service with a save() method for devices. This method is annotated as @Transactional. As a part of our business logic we need to update an attribute in the user that belongs to the device (via the organisation) whenever a device is created. Please don't ask for the reason - it's too complicated to explain here.
The problem is that devices can be created in two different ways: from the GUI and by an automated service that calls a servlet. Therefore the save() method is called in two different ways which comes with different object states and I don't know how to implement the save() method correctly.
GUI way:
Code:
### GUI layer (client) ###
// loading GUI
Organisation organisation = organisationService.findByName("MyOrganisation);
// user is creating a new device
Device d = new Device();
organisation.addDevice(d);
deviceService.save(d);
### BL2 layer (server) ###
@Transactional
public void save(Device device) {
// device is transient
// organisation and user are detached (they have a session, but it's closed)
}
Servlet way:
Code:
### external progamm (client) ###
// calls servlet with some parameters like deviceName
### BL1 layer (server) ###
@Transactional
public void createDevice(String deviceName) {
Organisation organisation = organisationService.findByName("MyOrganisation);
Device d = new Device();
organisation.addDevice(d);
deviceService.save(d);
}
@Transactional
public void save(Device device) {
// device is transient
// organisation and user are persistent and attached to the current session
}
How do I have to implement the save() method to persist the device and the change of the user? I tried something like:
Code:
@Transactional
public void save(Device device) {
final User user= device.getOrganisation.getUser();
user.setSomeAttribute("foo");
return deviceDao.save(device);
}
That works fine for the servlet way as the user is attached to the session and gets updated automatically when the transactions ends, but it won't work for the GUI way as the changes are made to a detached user object.
Can anyone please give me a wink to the right direction?
Thanks in advance,
Ole