无法将数据库状态与会话同步 org.hibernate.exception.GenericJDBCException:无法更新
我在尝试更新数据库时遇到此错误。我的数据库中没有定义唯一键,但id字段已被定义为主键。
以下是更新功能的代码:
public String updateAction(){
Session session = null;
try{
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
org.hibernate.Transaction tx = session.beginTransaction();
Medicine medicine = (Medicine) session.load(Medicine.class, id);
medicine.setBrandName(brandName);
session.update(medicine);
tx.commit();
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
session.close();
}
return "index";
}
hibernate.config.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">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/medicine</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</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.jdbc.factory_class">org.hibernate.jdbc.NonBatchingBatcherFactory</property>
<mapping resource="mediview/Medicine.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Medicine.java:
public class Medicine implements java.io.Serializable {
private String id;
private String brandName;
public Medicine() {
}
public Medicine(String id) {
this.id = id;
}
public Medicine(String id, String brandName) {
this.id = id;
this.brandName = brandName;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getBrandName() {
return this.brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
}
Medicine.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 14 Aug, 2013 8:46:46 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="mediview.Medicine" table="medicine" catalog="medicine">
<id name="id" type="string">
<column name="ID" length="5" />
<generator class="assigned" />
</id>
<property name="brandName" type="string">
<column name="BrandName" length="30" />
</property>
</class>
</hibernate-mapping>
答案 0 :(得分:2)
在执行更新之前刷新会话状态。
Medicine medicine = (Medicine) session.load(Medicine.class, id);
session.refresh( medicine );
http://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html_single/#d0e1718