我在Hibernate 4.1.4.Final
实现上使用 JPA。我的问题是我无法EntityManager#remove()
工作。所有其他:更新、插入、选择操作都工作得很好,除了这个。
我的persistence.xml
文件:
<persistence-unit name="myEntityManager">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>core.entity.Answer</class>
<class>core.entity.BaseEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
我的Answer
实体:(BaseEntity 类只保存主键 - ID)
@Entity
@Table(name = "ANSWER")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Answer extends BaseEntity {
@Column(name = "ANSWER_VALUE")
private String answerValue;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "QUESTION_ID", nullable = false)
private Question question;
//overrided equals, hascode, toString
// all getters and setters
}
调用时:
public void remove(T entity) {
this.entityManager.remove(this.entityManager.merge(entity));
}
也试过:
this.entityManager.remove(entity);
和:
T ref = entityManager.getReference(entityClass, primaryKey);
entityManager.remove(ref);
不走运:(它没有Answer
从数据库中删除记录。
我正在使用 Spring 配置来配置实体管理器,如下所示:
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"/>
<property name="persistenceUnitName" value="myEntityManager"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager"/>
remove
在带有注解的方法中调用@Transactional
。所以这不应该是交易问题。
我已启用 Hibernate SQL 日志记录,以及所有其他日志记录。我在任何地方都看不到delete
将执行查询或任何错误。
我真的没有选择。请指教。
编辑
也许这也会有所帮助:
我正在从另一个实体获得答案列表。答案是这样定义的:
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "evaluationPart")
private List<Answer> answers = new LinkedList<>();
像这样调用删除:
List<Answer> answers = evaluationPart.getAnswers();
if (answers != null && answers.size() > 0) {
for (Answer answer : answers) {
answerFacade.remove(answer); //This calls enetityManager.remove
}
}