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

Hibernate does not persist all fields of an object

我有以下实体

@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);

出于某种原因,这不会保留在数据库中。我看到正在对 DAO 方法进行调用,并且在日志中没有看到任何错误。但是这个字段并没有保存在数据库中(虽然保存了对象)

我认为 session.merge() 调用存在一些问题。如果我删除它以便它只保存对象,它会为该对象创建一个新行,但会保存新字段。有什么我想念的吗?

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

我还在调用合并之前验证了该字段的值,它是新值。为什么这没有反映在数据库中?

我也尝试了以下方法而不是合并

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();
    }

}