在获取max id时,Hibernate会给我一个旧对象

时间:2017-09-05 21:08:22

标签: c# hibernate

我正在使用带有spring mvc的hibernate。 我正在为整个Web应用程序使用单个会话工厂实例/线程。 我基于每个请求使用会话对象。

我正在获取最大ID,它正在给我正确的值,然后我使用相同的增量最大id更新表中的内容。

我面临的问题是,当我再次获取最大ID时,它会给我相同的先前最大ID但不会更新。

棘手的部分是,如果我再次尝试异常,那么它会给我正确的最大id值。

注意: - 在每次获取最大ID时我打开一个新的会话对象,然后最后关闭它。

这是我的代码: -

public class MyModel
{
    [JsonProperty(PropertyName = "singleVal")]
    public string MyVal { get; set; }
    [JsonProperty(PropertyName = "selectedVals")]
    public string[] MyVals { get; set; }
}

public class MyController
{
    public JsonResult DoSomething([FromBody] MyModel model)
    {
        // You will have access to the form values here, including the strings selected from your multi-select field
    }
}

第二次编辑: 保存此对象后,我使用以下代码更新数据库中的同一对象:

public static void prepareLogin(HttpServletRequest request,
            String loggedUser, int loggedUserType, int loggedUserId) {


        Session session = HibernateUtil.openSession();
        Transaction tr = session.beginTransaction();

        // fetching the max id from login manager table to update the login and
        // logout or various details
        int loginManagerMaxIdInt = 0;
        Criteria c2 = session.createCriteria(LoginManager.class);
        c2.addOrder(Order.desc("id"));
        c2.setMaxResults(1);
        LoginManager loginManager = (LoginManager) c2.uniqueResult();
        if (loginManager != null) {
            loginManagerMaxIdInt = loginManager.getId();
        }

        loginManagerMaxIdInt++;

        System.out.println("logManId: " + loginManagerMaxIdInt);

        // preparing the new loginManager object to be stored in the DB
        LoginManager newLoginManager = new LoginManager();
        newLoginManager.setId(loginManagerMaxIdInt);
        newLoginManager.setUserId(loggedUserId);
        newLoginManager.setLoginTime(new Date(System.currentTimeMillis()));
        UserTypeMaster userTypeMaster = new UserTypeMaster();
        userTypeMaster.setId(loggedUserType);
        newLoginManager.setUserTypeMaster(userTypeMaster);

        // binding the username, userType and loginManager id value to
        // the session
        // object
        request.getSession().setAttribute("loggedUser", loggedUser);
        request.getSession().setAttribute("loggedUserType", loggedUserType);
        request.getSession().setAttribute("loggedLoginManagerId",
                loginManagerMaxIdInt);

        // finally saving it and commiting
        session.save(newLoginManager);
        tr.commit();
        session.close();

    }

注意:如果我没有通过第二种方法,那么我的代码工作正常。即如果我只保存新对象,那么一切都很好,最大ID也可以完美获取。

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

首先抱歉在这篇文章中我的错误提问。

问题与此<property name="hibernate.connection.isolation">2</property>有关。

我在配置文件中添加了上面的代码,现在一切都很好。

答案 1 :(得分:-1)

了解会话刷新,它将会话数据与数据库同步。如果您的会话未同步,您将看不到更新的数据。

示例:刷新会话在提交/更新行之前,您将看不到预期的结果,但是下一次刷新应该执行该操作(与数据库同步会话)。

在异常之后,您打开一个具有实际数据库状态的新会话,这就是它工作的原因。