English 中文(简体)
B. 向实体提供最新信息的途径
原标题:Correct way to update entities on Hibernate + Spring

我有这个问题:

i 与实体编写意见

@RequestMapping("/admin/modifyImplant/{id}")
 public ModelAndView modifyImplant(@PathVariable Integer id) {
  ModelAndView mav = new ModelAndView();

  Implant currentImplant =impDAO.findById(id); //this is the dao
  Implanttype it= currentImplant.getImplanttype();
  Implantinverter ii=new Implantinverter();
  ArrayList<Implantpanel> implantpanels = new ArrayList<Implantpanel>();
  try{
      ii= (Implantinverter)currentImplant.getImplantinverters().toArray()[0];
      implantpanels=(ArrayList<Implantpanel>) imppanelDAO.findByProperty("implant",currentImplant );
  }
  catch (Exception ex){
      //TODO
  }
  mav.addObject("implantpanels", implantpanels);
  mav.addObject("implantinverter",ii);
  mav.addObject("implant", currentImplant); //THIS IS THE ENTITY I MEAN
  mav.addObject("implanttype",it);
  mav.setViewName("/implant/modifyImplant.jsp");

  return mav;


}

该法典对 j(略为部分代码)的做法

<form:form action="${pageContext.request.contextPath}/admin/finalizeModifyImplant/${implant.id}" method="POST" modelAttribute="implant">
        <table cellpadding="0" cellspacing="0" id="viewTable" >
            <tbody>
                <tr>
                <td class="label">
                    Name:
                </td>   
                <td>    
                    <form:input  id="User_namesurname" path="businessname" cssStyle="width:300px;"/>
                </td>
                </tr>

and so on for the fields of entity. The entity has some entity related, connected by foreign key ( like implanttype, implantinverter, implantpanels ).

The submission go to this controller:

 @RequestMapping(value = "/admin/finalizeModifyImplant/{id}",
method = { RequestMethod.GET,RequestMethod.POST })
public ModelAndView finalizeModifyImplant(@PathVariable int id, @Valid @ModelAttribute Implant implant, BindingResult result){
    ModelAndView mav=new ModelAndView();
    mav.setViewName("../../admin/modifyImplant/"+id);
    if (result.hasErrors()){
        return mav;
    }

    implant.setId(id); //NOTICE WHAT I NEED TO DO HERE!
    Implant oldImplant= impDAO.findById(id);
    implant.setImplantinverters(oldImplant.getImplantinverters());
    implant.setImplantpanels(oldImplant.getImplantpanels());
    implant.setImplanttype(oldImplant.getImplanttype());
    implant.setInverters(oldImplant.getInverters());
    implant.setPvgis(oldImplant.getPvgis());
    try{
        impDAO.merge(implant); //here i call getSession().merge()
    }catch(RuntimeException re){
        return mav;
        //TODO: errors
    }

when i get the form submission (this is an update) i have the following problems: 1. the returning implant has no id (field id=null) 2. the related entities are also null.

以下是移植实体:

public class Implant implements java.io.Serializable {
// Fields
private Integer id;
private Pvgis pvgis;
private Gateway gateway;
private Implanttype implanttype;
@JsonIgnore //I NEED TO JSONIGNORE IT BECAUSE IT HAS A RECURSIVE CALL ON IMPLANT
private Users users;
@NotEmpty
private String nameimplant;
private String place;
private double latitude;
private double longitude;
private double expectedpower;
private double tolerance;
[...] and many other fields

和相关的移植。

<hibernate-mapping>
<class name="it.pstmarche.model.Implant" table="implant" schema="public">
    <id name="id" type="integer">
        <column name="id" />
        <generator class="identity" />
    </id>
    <many-to-one name="pvgis" class="it.pstmarche.model.Pvgis" fetch="select">
        <column name="idpvgis" />
    </many-to-one>
    <many-to-one name="gateway" class="it.pstmarche.model.Gateway" fetch="select">
        <column name="idgateway" />
    </many-to-one>
    <many-to-one name="implanttype" class="it.pstmarche.model.Implanttype" fetch="select">
        <column name="implanttype" />
    </many-to-one>
    <many-to-one name="users" class="it.pstmarche.model.Users" fetch="select" >
        <column name="iduser" />
    </many-to-one>
    <property name="nameimplant" type="string">
        <column name="nameimplant" not-null="true">
            <comment>Name</comment>
        </column>

i 确实无法说明如何正确进行更新,因为当试图从db(通过发现ById或直接询问)获得更新的实体时,有时会得到正确和最新的实体,有时会让老的实体! 实际随机。

I tried: 1. removing the cache ( session.setCacheMode(CacheMode.IGNORE); ) with no result 2. adding getSession().flush(); getSession().close(); at the end of the merge method, that:

public void merge(Implant currentImp){
    //Session session = HibernateSessionFactory.getSessionFactory().openSession();
    Transaction tx= getSession().beginTransaction();
    if (currentImp.getId() != null) { // it is an update
        getSession().merge(currentImp);
        tx.commit();
        //getSession().update(currentImp);
        log.debug("MERGE");
        getSession().flush();// THAT S THE ADD
        session.close(); //THIS IS ALSO
    } else { // you are saving a new one
        getSession().saveOrUpdate(currentImp);
        tx.commit();
        getSession().flush();
        getSession().close();
        log.debug("Save sou");
    }

确实,我无法以正确的方式执行“温得和春天”的更新。 感谢任何帮助。 成就

www.un.org/spanish/ga/president 也许我的问题不明确。 目前的问题是:, 之后是: 实体在搜查该实体时(例如通过询问发现ById(int id))随机抽取旧实体(即认为该实体仍在解放会议)。 解决这一问题的唯一途径是取消会议(getSession(),但在此之后,i显然获得拉齐例外——无代理。 当我试图让实体的相关实体参与清理会议时! that

2EDIT: Thanks Tim H. However, i still facing issues related to handling hibernate sessions. preface: i use hibernate session per-thread, like

private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private  static Configuration configuration = new Configuration();    
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
    try {
        configuration.configure(configFile);
        sessionFactory = configuration.buildSessionFactory();
    } catch (Exception e) {
        System.err
                .println("%%%% Error Creating SessionFactory %%%%");
        e.printStackTrace();
    }
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    if (session == null || !session.isOpen()) {
        if (sessionFactory == null) {
            rebuildSessionFactory();    
        }
        session = (sessionFactory != null) ? sessionFactory.openSession()
                : null;
        threadLocal.set(session);
    }
    return session;
}

现在,suppose iload entities x from the db, on Tomcat thread 1。 实体价值为100。 在装满后,我无法结束本届会议(如果会议闭幕,即risk,以获得“酶初始化”例外——没有Proxy/session)。

After, i update the value of entity x on thread 2. The value now is 50.

最后,一把价值重新装上,但去门到一面,在该地,该实体仍在深层的届会上,其价值仍为100。 我拿到了老的价值观,而不是新的价值!

因此,在我支离破碎之前,我无法结束本届会议(即使用 la场),我不得不通过下列途径在届会结束时结束会议:和lt;% HibernateSessionFactory.getSession(......);%>而且这可怕! i 加上这一模式的看法! 是否有安全这样做的模式?

问题回答

我也许能够说明你的一些问题。

  1. 如果申请参数与贵实体(隐形形式领域)的赠与财产相符,则贵方将受其实体的约束。

  2. 对于其他具有约束力的人,你可能希望使用所谓的“@ModelAttribute”骗局。 基本上,所有要求都要求采用附加说明的任何方法,因此,这种方法将退回到“春天”将构成对你背后物体的附后实体,如此。

    @ModelAttribute Implant implant public Implant getBackingImplant(HttpServletRequest request) { if(request.getParameter("id") != null return dao.getImplantByIdWithAllMyRelationshipsFilledIn(request.getParameter("id");

    return new Implant(); }

如今春天,你对通过移植而返回的实体的形式具有约束力。

如果你不工作,我真的不相信我不会有一席之地,但上面应该解决你具有约束力的伤口。

添加新的答案,因为这个问题现在更为明确。 放弃合并后的实体,你将放弃你合并指挥的结果,相反,你应将这一结果退回到你的控制人员。





相关问题
Write-though caching of large data sets in WCF?

We ve got a smart client that talks to a SQL Server database via WCF, displaying the entities in the database, and allowing the user to edit those entities. Some of the WCF calls return a large data ...

Clearing RSL in Cache

I have built a flex application which has a "main" project and it is assosciated with a few RSL s which are loaded and cached once i run my "main" application. The problem i am facing is that the ...

how to tell clicking "back" to load cache?

I would like for my site when someone clicks "Back" or "Forward" for the server to tell the browser to load the cache instead of reloading the entire page. I ve tested some headers and done research, ...

java plugin cache and dynamic IP host

I m trying to use Amazon S3 and Amazon Cloudfront CDN to deliver the jar files of my applet application. I m seeing several cache misses of my jars by the java plugin. This is a show-stopper for me, ...

Frequently Used metadata Hashmap

Are there any implementations of a static size hashtable that limits the entries to either the most recently or most frequently used metadata? I would prefer not to keep track of this information ...

PHP - Memcache - HTML Caching

I would like to create a caching system that will bypass some mechanisms in order to improve the performance. I have some examples: 1-) I have a dynamic PHP page that is updated every hour. The page ...

Performance of Sql subqueriesfunctions

I am currently working on a particularly complex use-case. Simplifying below :) First, a client record has a many-to-one relationship with a collection of services, that is, a single client may have ...