尝试使用SQLight Hybernate运行简单的Java项目。有例外:

Deleting Doc
Hibernate: delete from Doc
Updating document, DocID = 2, Name = doc 2
Hibernate: update Doc set DocName=?, Job=? where Id=?
exception Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
Jun 15, 2016 3:30:03 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
    at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
    at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:47)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2574)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2478)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2805)
    at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:114)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:259)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:179)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at hyberntst.Db2.close(Db2.java:46)
    at hyberntst.Db2.saveDoc(Db2.java:75)
    at hyberntst.HybernTst.main(HybernTst.java:19)


我在data.db中有空表Doc

CREATE TABLE `Doc` (
    `Id`    INTEGER PRIMARY KEY AUTOINCREMENT,
    `DocName`   TEXT,
    `Job`   TEXT
)


Hybernate配置-hybernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">hyberntst.SQLiteDialect</property>
    <property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
    <property name="hibernate.connection.url">jdbc:sqlite:data.db</property>
    <property name="hibernate.connection.pool_size">1</property>
    <property name="hibernate.show_sql">true</property>
    <!--property name="hibernate.current_session_context_class">thread</property-->
    <!--property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property-->
    <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <mapping resource="hyberntst/Doc.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


负责处理数据库的类:

package hyberntst;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Db2 {

    private SessionFactory sessionFactory;
    private Session session;

    Db2() {

        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    //------------------------------------------------------------------------------------------------------------------
    private void open() {
        session = sessionFactory.openSession();
        session.beginTransaction();
    }

    private List query(String hql) {
        Query query = session.createQuery(hql);
        return query.list();
    }

    private void executeUpdate(String hql) {
        Query query = session.createQuery(hql);
        query.executeUpdate();
    }

    private void close() {
        session.getTransaction().commit();
        session.close();
    }

    public void deleteDoc() {
        try {
            open();

            log.finer("Deleting Doc");
            executeUpdate("delete Doc");

            close();
        } catch (Exception ex) {
            log.logExept(ex);
        } catch (Error err) {
            log.warning(err.toString());
        }
    }

    public void saveDoc(Doc doc) {
        try {
            open();
            log.finer("Updating document, DocID = " + doc.getId() + ", Name = " + doc.getDocName());
            session.saveOrUpdate(doc);

            close();
        } catch (Exception ex) {

            log.logExept(ex);
        }

    }

}


用于写入数据库的Doc类:

public class Doc {
     private Integer id;


    public Integer getId()
    {
        return this.id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    private String docName;

    public String getDocName()
    {
        return this.docName;
    }

    public void setDocName(String docName)
    {
        this.docName = docName;
    }

    private String job;

    public String getJob()
    {
        return this.docName;
    }

    public void setJob(String job)
    {
        this.job = job;
    }


}


“主要”代码:

Doc d = new Doc();
d.setId(new Integer(2));
d.setDocName("doc 2");
d.setJob("job 2");

Db2 db2 = new Db2();
db2.deleteDoc();
db2.saveDoc(d);


在这里您可以看到我使用的库:

java -  Hello World  hibernate-LMLPHP

看起来从数据库中删除可以正常工作,但是插入又有什么问题呢?

日志文件中的问号是什么?

Hibernate: update Doc set DocName=?, Job=? where Id=?

最佳答案

通常,如果实体id不为null,则休眠将执行更新。
更多信息here


  saveOrUpdate()执行以下操作:
  
  
  如果对象已在此会话中保持不变,则不执行任何操作
  与该会话相关联的另一个对象具有相同的标识符,
  抛出异常
  如果对象没有标识符属性,请保存()
  如果对象的标识符具有分配给新实例化的对象的值,则将其保存()
  如果对象由或进行版本控制,并且版本属性值与分配给新对象的值相同
  实例化对象,将其保存()
  否则update()对象
  


您必须显式调用save()或将id保留为空

09-25 20:18