Question

I am just creating a settings page where a user can change his user name. The strange thing is I am using the same finder Method for displaying it in the main view and in the form but the objects are not related to each other.

The side effect is now, if I dont enter an username and click on save. Both objects are updated. As well the display in the view which is wrong.

I just want to use in the form a seperate model. What am I doing wrong here? I thought calling "Model.find" is returning me everytime a different reference of an object, even if its the same row in the db. Is play doing some intelligent caching here?

Its quite anoying as changing the user in the form means changing all other same user objects in the view.

Action for rendering the create/edit page:

public static void index(){
        User appUser = User.findUser(SecureSocial.getCurrentUser().id);
        render(appUser);
 }

My view(which displays the current logged in username)

${models.User.findUser(user.id).username}

My model:

public static User findUser(UserId userId){
        User user = User.find("externalId = ? and provider = ?", userId.id, userId.provider.name()).first();
        return user;
}

Thanks

Was it helpful?

Solution

Hibernate is backing your persistent storage. Hibernate will, for one persistent (logical) object in one Transaction, only create and keep one instance of it around for many reasons. So the behavior you describe is actually to be expected.

For more on that, see http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview.

To have two instances of your object around at the same time, you have to detach (ie. remove the link to the DB object in Hibernate's parlance) it. Typically you detach the object which is edited, and let the object for the rendering alone.

So you would change your controller function to detach the object which is edited:

User.em().detach(user);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top