skywalker
skywalker

Reputation: 716

Hibernate does not create a new entry in table

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!

Upvotes: 0

Views: 86

Answers (1)

skywalker
skywalker

Reputation: 716

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.

Upvotes: 1

Related Questions