0

I have question. Is it possible to create new entry in the db if the entry does not exist? If it exist it should update the current entry.

I have something like this:

@Transactional
public void saveSettingsForUser(String userId, SettingsMessageModel settings) {
    Session session = getSessionFactory().getCurrentSession();
    UserSettings userSettings = new UserSettings();
    userSettings = (UserSettings) session.load(UserSettings.class, userId);
    userSettings.setUserId(userId);
    userSettings.setAutoanswer(settings.isAutoanswer());
    userSettings.setDnd(settings.isDnd());
    session.save(userSettings);
}

It works for entries that are already in the db. But if I want to save new one with primery key userId it does not allow me. Any suggestion is appreciated. Thank you!

skywalker
  • 696
  • 2
  • 16
  • 37
  • [This answer](http://stackoverflow.com/a/161358/785663) states `save()` will do what you want. Can you include more information how you determine that "it does not allow me"? – mabi Jun 04 '15 at 11:29

1 Answers1

1

I managed to create new entry if such id does not exist with the following code:

@Transactional
public void saveSettingsForUser(String userId, SettingsMessageModel settings) {
    Session session = getSessionFactory().getCurrentSession();
    UserSettings userSettings = (UserSettings) session.get(
            UserSettings.class, userId);
    if (userSettings == null) {
        userSettings = new UserSettings();
    }

    userSettings.setUserId(userId);
    userSettings.setAutoanswer(settings.isAutoanswer());
    userSettings.setDnd(settings.isDnd());
    session.saveOrUpdate(userSettings);
}

Instead of session.load() I use session.get() method. This approach allows me to check if there is an entry in the db and if there is not I create it. Hope it will help somebody else.

skywalker
  • 696
  • 2
  • 16
  • 37