在我的 Controller 中,将MySQL数据库中的值放入ModelAndView object

有一个单独的程序来更新表,并且 MVC 应该获取该值,因此没有表单可以更新该表。

表更新为时,并且当我在浏览器上命中刷新时,这些值将不会在页面上更新。

Controller

@SuppressWarnings("unchecked")
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
@RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public ModelAndView defaultPage(@ModelAttribute("user") User user) {
    Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder
            .getContext().getAuthentication().getAuthorities();
    ModelAndView view = new ModelAndView("/hello");
    // Redirects to admin page if user has admin role
    if (authorities.toString().contains("ROLE_ADMIN")) {
        return new ModelAndView("redirect:/admin");
    }
    /////
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String userName = auth.getName();
    User userInfo = userDAO.getUserInfo(userName);
    System.out.println("Here's the thing " + userInfo.getLastname() + " " + userInfo.getUserDetails());
    Details details = userDAO.getDetailsInfo(userInfo.getUserDetails().getLastname(),
            userInfo.getUserDetails().getPostcode());
    Plugs plugs = userDAO.getPlugInfo(details.getMacAddress());
    String json = plugs.getJson();
    JSONObject obj = new JSONObject(json); //this is the value that is not updating
    String name = obj.getJSONObject("meta").getJSONObject("locate").getString("value");
    System.out.println(name);
    view.addObject("json", obj);
    return view;
}

我知道这很被看不起,但是我把这个值放在 Javascript中。

像这样:
<c:set var="json" value="${json}"/>

var __data__ = ${json};

为什么在更新数据库时MVC无法显示正确的值?

我希望它在刷新时更新

最佳答案

绝对PersistenceContextType.EXTENDED范围是您确定的问题的根本原因。原因如下:

通过PersistenceContextType.TRANSACTION范围,Spring框架负责管理注入(inject)的entitymanager的生命周期。 TRANSACTION范围的生命周期与基础transaction绑定(bind)在一起,并且在提交/回滚事务后,springt框架会关闭entityManager

但是对于PersistenceContextType.EXTENDED范围,Spring框架仅负责注入(inject)entitymanagerEXTENDED范围内的实体管理器的生命周期与用户transaction无关,它可以跨越多个事务。应用结束后,由应用程序/用户来明确关闭entityManager。如果没有,它将永远保持打开状态(或直到Spring容器关闭)。

我认为您的userDAO中没有明确关闭entityManager。而且“userDAO”也可以是单例。因此,仅一次注入(inject)的相同entityManager正在多个调用(或http请求)中使用

使用此entityManager' remains open forever and so when you try to access any object (User/Plugin/UserDetails) the entityManager`检查其一级缓存,它将检查它在其中找到的(第一次加载的)一级缓存,并从其一级缓存(陈旧)返回此对象,而不是命中数据的数据库。

显然,对于TRANSACTION范围,每当事务完成(或方法退出)时,Spring框架就会关闭entityManager。这将导致为每个请求(在您的情况下是Web请求)创建一个entityManager命中具有更新数据的数据库。

查看此链接是否有帮助。 http://forum.spring.io/forum/other-spring-related/ejb/18445-injection-of-persistencecontext-with-persistencecontexttype-extended

09-30 15:25
查看更多