Hibernate不持久化对象的所有字段

问题描述:

我有以下实体Hibernate不持久化对象的所有字段

@Entity 
@Table(name = "Example") 
@JsonIgnoreProperties(ignoreUnknown = true) 
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 


public class Example implements Comparable<Example>, Serializable { 


    private static final long serialVersionUID = 1L; 
    @JsonProperty 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    long id; 

    String fieldToPersist; 
} 

其DAO

public class ExampleDAO { 



    public SessionFactory sessionFactory; 
    public Session session; 

    public ExampleDAO(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
     this.session = sessionFactory.openSession(); 
    } 


    @Transactional 
    public void createOrSave(Example ex) { 
     Session session = sessionFactory.openSession(); 
     Transaction tx = session.beginTransaction(); 
     Example exExisting = getById(ex.id); 
     try { 
      if (exExisting != null) { 
       session.merge(ex); 
       tx.commit(); 
      } else { 
       session.save(ex); 
      } 
     } catch (RuntimeException e) { 
      tx.rollback(); 
     } finally { 
      session.close(); 
     } 

    } 

在我的代码

我设置

example.setFieldToPersist("abc") 
dao.createOrsave(example); 

对于某些原因,这不会持续在da tabase。我看到了对DAO方法的调用,并且在日志中看到没有错误。但是这个字段没有保存在数据库中(虽然保存了对象)

我相信session.merge()调用存在一些问题。如果我删除它只保存该对象,它会为该对象创建一个新行,但新的字段将被保存。有什么我失踪了吗?

我还注意到,第一次对对象进行更改并调用createOrSave()方法时,它正确地更新了对象。但将来调用这个方法似乎不会更新它?会话是否过时?日志是否应该提供一些相关信息?

我还在合并调用之前确认了字段的值,它是新的值。为什么这不反映在数据库中?

我也曾尝试follwoing方法,而不是合并

session.save() -- creates a new entry in the database with the updated values 
session.update() - no change 
session.saveOrUpdate() -- no change 
session.flush() -- no change 

试着改变你的createOrSave方法是这样的:

@Transactional 
public void createOrSave(Example ex) { 

    Session session = sessionFactory.openSession(); 
    Transaction tx = session.beginTransaction(); 
    //saving the getById on another variable 
    Example managedExample = getById(ex.id); 

    try { 
     if (managedExample != null) { 
      //if the entity exists, just merge 
      session.merge(ex); 

     } else { 
      session.save(ex); 
     } 
     tx.commit(); 
    } catch (RuntimeException e) { 
     tx.rollback(); 
    } finally { 
     session.close(); 
    } 

} 
+0

谢谢,改变它,但是似乎没有解决这个问题 –

+0

你还可以尝试致电 '示例ex = getById(ex.id); ' After: 'Transaction tx = session.beginTransaction();' – KuroObi

+0

同样的问题,尝试获取trabsaction后的对象开始 –