Hibernate сохраняет новый объект при каждом слиянии

StackOverflow https://stackoverflow.com//questions/10701928

Вопрос

У меня своеобразная проблема.Каждый раз, когда я вызываю слияние в сеансе, Hibernate сохраняет совершенно новый объект.Я использую Hibernate 3.6 в приложении Spring MVC.

Пожалуйста, найдите ниже мой код:

Мой hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        <property name="dialect">org.hibernate.dialect.Oracle10gDialect </property>





        <!-- this will show us all sql statements -->
        <property name="hibernate.show_sql"> true   </property>
        <property name="connection.pool_size">1</property>


        <!--  <property name="hbm2ddl.auto">create</property>-->

        <!-- mapping files -->


        <mapping resource="com/hibernate/hbm/employee.hbm.xml"></mapping>
        </session-factory>
</hibernate-configuration>

Мой сотрудник.hbm.xml

<hibernate-mapping default-lazy="true">
    <class name="com.spring.model.Employee" table="employee">
        <id name="empId" type="long" column="empId" unsaved-value="null">
            <generator class="sequence">
                <param name="sequence">hibernate_sequence</param>
            </generator>
        </id>
        <version name="version" column="version" unsaved-value="null"
            type="long" />


        <component name="identity" class="com.spring.model.Identity">
            <property name="firstname" column="firstname" not-null="true" />
            <property name="lastname" column="lastname" not-null="true" />
            <property name="email" column="emailid" not-null="true" />
        </component>


        <!--    <property name="birthday" column="birthday"/>       -->
        <property name="fileDataBytes" column="filedata" />

        <property name="fileName" column="fileName" />
        <property name="fileContentType" column="fileContentType" />

    </class>
</hibernate-mapping>

Мой классы моделей

  public class Employee  extends BaseModel{
   private CommonsMultipartFile fileData;


private byte[] fileDataBytes;
private String fileName;
private String fileContentType;

private Identity identity;

private long empId;
      //getters,setters /equals() on empId field 

       @Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (int) (empId ^ (empId >>> 32));
    return result;
}


@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Employee other = (Employee) obj;
    if (empId != other.empId)
        return false;
    return true;
}

       public class BaseModel implements Serializable{
       private Long version;

       //gettes,setters

      public class Identity {
       protected String firstname;   
protected String lastname;   
  protected String email;    
        //getters.setters

Мой сохранение сотрудникаDAOImpl.java метод

public long saveEmployee(Employee employee) throws Exception {
        public Employee getEmployeeById(long empId) {
        // TODO Auto-generated method stub
        return (Employee) getSessionFactory().getCurrentSession().load(Employee.class,empId);
                       }
    }
        // TODO Auto-generated method stub
        if(employee.getEmpId() == 0){
             return  (Long)getSessionFactory().getCurrentSession().save(employee);
        }else{
            Employee empInSession = getEmployeeById(employee.getEmpId());
            getSessionFactory().getCurrentSession().merge(employee);
            return  employee.getEmpId();

        }
    }

Примечание :я уже загрузил объект в цикле GET, но чтобы гарантировать, что объект загружен в кеш, я все еще загружаю его перед вызовом merge(). В идеале слияние вообще не должно требоваться, поскольку объект становится постоянным.Почему, черт возьми, это происходит?Hibernate сохраняет новый объект с измененными свойствами и сохраняет его.Разве он не должен проверять поле empId, которое находится в проверке равенства??

Это было полезно?

Решение 2

Ну, похоже, это проблема Spring.Проблема решена добавлением @SessionAttributes в мой класс контроллера. Кажется безобидным, но на самом деле это был корень проблемы.Мартен на форуме Spring мне помогает здесь

Другие советы

Попробуйте добавить равенство и хэш-код в свой класс сотрудников.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top