我使用时遇到问题EntityManager.persist(Object)
方法。现在,当我摆脱其他问题时,通过应用程序工作没有异常,但对象没有放入我的数据库中。
我的实体类:
@Entity
@Table(name ="Chain")
public class Chain implements Serializable{
@Id
@Column(name = "id")
private Long id;
@Column(name = "date")
private Date date;
@Column(name = "name")
private String name;
//setters and getters
}
我的 dao 类:
@Transactional
@Repository("ChainDao")
public class ChainDaoImpl implements ChainDao{
private EntityManager em;
@PersistenceContext
public void setEntityManager(EntityManager em) {
this. em = em;
}
public int saveChain(Chain chain) {
chain.setDate(new Date());
chain.setId((long)44);
Boolean a;
em.persist(chain);
return 222;
}
}
我的 xml 上下文:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property></bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
and pereistence.xml
:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="sample">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- Scan for annotated classes and Hibernate mapping XML files -->
<properties>
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/database"/>
<property name="hibernate.connection.username" value="postgres"/>
<property name="hibernate.connection.password" value="pwd"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
有谁知道我错过了什么?
您是否遇到特定的例外情况?如果您是的话,知道它是什么会很有帮助。
Stackoverflow 上已经存在许多与此类似的问题:
Spring事务上下文不持久保存数据 https://stackoverflow.com/questions/5265783/spring-transactional-context-doesnt-persist-data?rq=1
Spring、Hibernate 和 JPA:在实体管理器上调用 persist 似乎没有提交到数据库 https://stackoverflow.com/questions/374886/spring-hibernate-jpa-calling-persist-on-entitymanager-does-not-seem-to-commi?rq=1
这些建议您应该尝试添加em.flush()
之后em.persist(chain)
,并改变@transactional
注释
您还应该检查是否已通过以下行启用事务注释:
<tx:annotation-driven transaction-manager="transactionManager"/>
在你的 .xml 配置中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)