Back Forum Reply New

Hibernate object mutation question

Hi!

I've created a Hibernate entity, which is more or less the following:

@Entity
class Directory {

Integer id;

String name;

Directory parent;

Listlt;Directorygt; subdirectories;
}

My question:

How to implement the changeName(String name) method of this class? It should work in the following way:

1. Check, if there is no subdirectory in the parent directory by this name
2. Change the name field.

Two questions arise:

How to make the changeName method transactional?
How to create a query within this entity, to search for subdirectories by a given name?

One possibility would be to factor this method out into a service method, but I'd be curious if you have any better ideas.

Answer to the first question:

in a lot of cases you don't want to have a transaction around the domain objects themselves. I prefer having some service layer that is made transactional and this layer can call the domain objects. This means that the same methods of domain objects could be part of transactions with different scopes (so maybe 1 domain object gets modified... or 100... it doesn't matter).

So in your case:Code:
class OwnerService{          @Transactional      void changeOwner(String dir, String owner){  Directory dir = dirDao.find(dir);  dir.setOwner(owner);      }
}
In most cases the Service is quite thin (the logic can be moved in the domain objects themself).
¥
Back Forum Reply New