java - Hello World hibernate

标签 java database hibernate sqlite

尝试使用 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中有空表文档

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>

负责处理DB的类:

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

    }

}

用于写入数据库的文档类:

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

在那里你可以看到我使用的库:

enter image description here

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

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

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

最佳答案

一般情况下,如果entity id不为null,hibernate就会执行更新。 更多信息here :

saveOrUpdate() does the following:

  • if the object is already persistent in this session, do nothing if another object associated with the session has the same identifier, throw an exception
  • if the object has no identifier property, save() it
  • if the object's identifier has the value assigned to a newly instantiated object, save() it
  • if the object is versioned by a or , and the version property value is the same value assigned to a newly instantiated object, save() it
  • otherwise update() the object

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

关于java - Hello World hibernate ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37854121/

相关文章:

java - 我正在尝试将我的应用程序从 Spring 转移到 Spring Boot,但遇到了一些问题。特别是以下异常

java - 是否可以使用 Hibernate Validator 设置验证顺序?

java - android studio 3.1不显示光标所在的功能

java - ArrayList Hash Map 提取并存储到 arraylist

java.awt.image.BufferedImage 使用自定义 ColorSpace 将 24 位 RGB 转换为 8 位灰度

java - GlassFish v3 - 设置的可移植性

mysql - 数据库行之间的相互关系

json - REST API 状态是整数还是字符串?

mysql - WITH ROLLUP 和 DISTINCT 的错误使用

java - 获取类的字段