gpt4 book ai didi

spring - EntityManager persist() 方法不向数据库插入记录

转载 作者:IT老高 更新时间:2023-10-28 13:49:03 26 4
gpt4 key购买 nike

我在使用 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
}

我的道课:

@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>

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 transactional context doesn't persist data

Spring, Hibernate & JPA: Calling persist on entitymanager does not seem to commit to database

这些建议您应该尝试在 em.persist(chain) 之后添加 em.flush(),并更改 @transactional注释

您还应该通过以下行检查是否启用了事务注释:

<tx:annotation-driven transaction-manager="transactionManager"/> 

在您的 .xml 配置中

关于spring - EntityManager persist() 方法不向数据库插入记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13759894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com