问题是下面的代码片段没有删除数据库中的记录。
import org.hibernate.Session;
import org.hibernate.SessionFactory;
...
...
void deleteForm() {
Session session = sessionFactory.openSession();
FormDO formDO = new FormDO();
formDO.setId(formId);
session.delete(formDO); // No delete SQL query is getting fired.
但是,如果我在删除后调用 session.flush(),它会完美运行。请注意,我没有使用任何交易。
在Session类的JavaDoc中对delete方法的描述是:
Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with existing persistent state.
而且我在网上看到很多代码片段表明在delete()之后没有必要调用flush()。其他论坛也有类似问题here但仍未得到答复。
此外,session.save 在没有 session.flush 的情况下也能正常工作。
我正在使用 Hibernate 4.2.16 + Spring 4.0.9 + JPA 1.0 注释。以下是供进一步引用的源文件,
FormDO.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="form")
public class FormDO {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
Integer id;
@Column(name="name")
String name;
...
...
Spring 配置文件
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/tempdb" />
<property name="username" value="root" />
<property name="password" value="****" />
</bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.test.FormDO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
FormDAO.java
@Named
public class FormDAO {
@Inject
private SessionFactory sessionFactory;
public boolean deleteForm(Integer formId) {
Session session = sessionFactory.openSession();
FormDO formDO = new FormDO();
formDO.setId(formId);
session.delete(formDO);
session.flush(); // If this line is commented, record DOES NOT get deleted
return true;
}
public boolean saveForm(FormDO formDO) {
Session session = sessionFactory.openSession();
session.save(formDO); // Save doesn't require session.flush
return true;
}
...
...
更新:
我的困境主要是由于不一致。session.save 立即插入记录,但 session.delete 不会反射(reflect),除非显式调用 flush()。但是当我引用 Flushing the Session Afsun 发布的链接,通过阅读以下行消除了我的疑虑,
An exception is that objects using native ID generation are inserted when they are saved.
我非常感谢每个人发布的答案,因为几乎所有答案都指向了正确的方向,但 Afsun 完全消除了我的疑虑。谢谢!
最佳答案
当您通过 Hibernate 使用数据库时,您正在使用 Hibernate session 。 Hibernate session通过以下三种情况刷新到数据库。
commit()- 当您提交事务时session.flush()这里最重要的是第二个。每次查询后,Hibernate session 都不会刷新数据库。如果我们通过 Hibernate 运行 Native SQL Query,Hibernate 不知道刷新 session ,或者如果运行 HQL,Hibernate 也不知道刷新 session 。调用 flush 将使 session 状态与数据库同步。
请参阅以下内容:
Hibernate flush before delete和 Flushing the Session
关于java - 为什么在 Hibernate 中需要在 session.delete() 之后调用 session.flush()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30215081/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象