我在“这么长的帖子必须意味着大量的代码和配置”部分下一对一地使用指南代码。
http://blog.springsource.com/2006/08/07/using-jpa-in-spring-without-referencing-spring/
问题是,只有类似选择的查询才有效。当我尝试保留 bean/entity 时,查询不会发生(我已为 Hibernate 设置了 show sql 选项)。我知道这可能与 Spring 配置有关,但我没有寻找什么的经验。
Spring 配置:
<?xml version="1.0" encoding="UTF-8"?>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" />
<bean id="productDaoImpl" class="product.ProductDaoImpl"/>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
Dao:
@Repository
public class ProductDaoImpl implements ProductDao {
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this. entityManager = entityManager;
}
// works
public Collection loadProductsByCategory(String category) {
return entityManager.createQuery("from Product p where p.category = :category")
.setParameter("category", category).getResultList();
}
// Doesn't even get queried for
public void persistWhatever(Product product) { entityManger.persist(product); }
}
最佳答案
我猜测您的服务方法(调用 DAO 的方法)上没有 @Transactional
。通常,服务方法是放置@Transactional的地方(有些人将其放在DAO方法上,但这没有必要太细化)
关于java - Spring + Hibernate - 持久/提交数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5795245/