0

I am trying to save in same user_friend db table this relationship of friends, but only is persist in db one when method is ended.

@Override
@Transactional(readOnly = false)
public boolean saveLocalFriends(UserFriend userFriend) {

    UserFriend userFriendToRevert = userFriend;

    if (this.friendDao.saveFriend(userFriend)) {

        userFriendToRevert.revert();
        return this.friendDao.saveFriend(userFriendToRevert);
    }

    return false;
}

The good way to do this based in @macias contribution.

@Override
@Transactional(readOnly = false)
public boolean saveLocalFriends(UserFriend userFriend) {

    UserFriend userFriendToRevert = new UserFriend();
    BeanUtils.copyProperties(userFriend, userFriendToRevert);    

    if (this.friendDao.saveFriend(userFriend)) {

        userFriendToRevert.revert();

        return this.friendDao.saveFriend(userFriendToRevert);
    }

    return false;
}
Dani
  • 4,001
  • 7
  • 36
  • 60

1 Answers1

1

In the method posted by you, the single entity is saved twice. I'm not sure what the revert method does, but I assume it just changes the state of UserFriend in some way. The second save will basically overwrite the first one. Note that

UserFriend userFriendToRevert = userFriend;

copies just the reference. If your intention was to persist a modified copy of userFriend you need to do it hard way - construct a new UserFriend object and copy properties one by one, then persist the copy.

makasprzak
  • 5,082
  • 3
  • 30
  • 49
  • Thank you very much, I was assuming each call to save method in DAO was persisting the object independently. – Dani Jun 14 '14 at 20:35