Hibernate 无法将数据库状态与会话同步
无法将数据库状态与会话同步 org.hibernate.exception.genericjdbception:无法更新 我在尝试更新数据库时遇到此错误。我的数据库中没有定义唯一键,但id字段已定义为主键 以下是更新功能的代码:Hibernate 无法将数据库状态与会话同步,hibernate,jdbc,Hibernate,Jdbc,无法将数据库状态与会话同步 org.hibernate.exception.genericjdbception:无法更新 我在尝试更新数据库时遇到此错误。我的数据库中没有定义唯一键,但id字段已定义为主键 以下是更新功能的代码: public String updateAction(){ Session session = null; try{ SessionFactory sessionFactory = new Configuration(
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.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>
在更新之前刷新会话状态
Medicine medicine = (Medicine) session.load(Medicine.class, id);
session.refresh( medicine );
你能给我们实体和hibernate配置吗?我刚刚添加了hibernate配置文件。谢谢,然后我想我们可能需要“mediview/Medicine.hbm.xml”。我也添加了Medicine.hbm.xml。这一切看起来都很好。我不确定你的错误。您的数据库架构正确吗?您尝试过SQL hibernate生成吗?您可以通过hibernate.show\u sql属性打开它。@Arun但是为什么在这种情况下需要刷新?有没有办法在webservice客户端中实现这一点?是否在保存对象之前获取现有会话并刷新对象?
Medicine medicine = (Medicine) session.load(Medicine.class, id);
session.refresh( medicine );