spring EntityManager persist() 方法不会将记录插入数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13759894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
EntityManager persist() method does not insert record to database
提问by Grzzzzzzzzzzzzz
I have problem with using EntityManager.persist(Object)method. Now when i get rid of other problems, by app work without Exception but object is not put in my database.
我在使用EntityManager.persist(Object)方法时遇到问题。现在,当我摆脱其他问题时,通过应用程序工作而没有异常,但对象未放入我的数据库中。
my entity class:
我的实体类:
@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
}
my dao class:
我的道课:
@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;
}
}
my xml context:
我的 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:
和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>
Do anyone have a idea what am i missing?
有谁知道我错过了什么?
采纳答案by RoryB
Are you getting a specific exception? It would be helpful to know what it is if you are.
你得到一个特定的例外吗?如果你是,知道它是什么会很有帮助。
There are a number of similar problems to this already on Stackoverflow:
Stackoverflow 上已经有许多类似的问题:
Spring transactional context doesn't persist data
Spring, Hibernate & JPA: Calling persist on entitymanager does not seem to commit to database
Spring、Hibernate 和 JPA:在 entitymanager 上调用持久化似乎没有提交到数据库
These suggest that you should try adding em.flush()after the em.persist(chain), and altering the @transactionalannotations
这些建议您应该尝试em.flush()在 之后添加em.persist(chain),并更改@transactional注释
You should also check that you have enabled transactional annotations through a line such as :
您还应该检查是否已通过以下行启用事务注释:
<tx:annotation-driven transaction-manager="transactionManager"/>
in your .xml configuration
在您的 .xml 配置中
回答by Peter Adrian
Try this:
尝试这个:
em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();
PS: You should set a generation method for your ID as well.
PS:您还应该为您的ID设置一个生成方法。
回答by Bernardo Vale
Can you post what exception are you getting? I will assume that your error is that your persistence.xml you don't specified your "Chain" Object.
你能发布你得到什么例外吗?我会假设你的错误是你的 persistence.xml 你没有指定你的“链”对象。
You can specify using this tag
您可以使用此标签指定
<exclude-unlisted-classes>false</exclude-unlisted-classes>
Or just
要不就
<class>your.package.Chain</class>
Put this above providertag.
把这个放在提供者标签上面。
Also, never set a number for a column tagged as @Id
此外,永远不要为标记为@Id 的列设置数字
When you use method save() with a Id column with setted value, hibernate will try to UPDATENOT INSERT your data.
当您将方法 save() 与具有设置值的 Id 列一起使用时,hibernate 将尝试UPDATENOT INSERT 您的数据。
Do this: Create getEntityManager Method
这样做:创建 getEntityManager 方法
public EntityManager getEntityManager() {
return entityManager;
}
Then
然后
@Transactional
public void saveChain(Chain chain) {
chain.setDate(new Date());
getEntityManager().persist(chain);
}
回答by ElvisKang
Adding these to your web.xmlmay solve this problem:
将这些添加到您的web.xml可能会解决此问题:
<!-- Open Entity Manager in View filter -->
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
回答by Wilson Campusano
solved my problem using
使用解决了我的问题
org.springframework.transaction.jta.JtaTransactionManager
hope this work!
希望这项工作!
回答by Randy Orton
Use @EnableTransactionManagement in AppConfig Configuration file header
在 AppConfig 配置文件头中使用 @EnableTransactionManagement
回答by Rakesh Singh Balhara
You can open the new Transaction and then commit your records.
您可以打开新交易,然后提交您的记录。
@PersistenceUnit(unitName = "NameOfPersistenceUnit")
private EntityManagerFactory entityManagerFactory;
void someMethod(AccountCommodity accountCommodity){
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(accountCommodity);
entityManager.flush();
entityManager.getTransaction().commit();
entityManager.close();
}
回答by hlopezvg
I was able to fix the same problem by adding the Entity to persistence.xml:
我能够通过将实体添加到persistence.xml来解决同样的问题:
<persistence-unit name="OwnerPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.test.domain.local.Entity</class>
<exclude-unlisted-classes />
</persistence-unit>
</persistence>
回答by Jigar Parekh
You will need to assign id generation strategy as below:
您将需要分配 id 生成策略如下:
@Entity
@Table(name ="Chain")
public class Chain implements Serializable{
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column(name = "date")
private Date date;
@Column(name = "name")
private String name;
//setters and getters
}
and in save method
并在保存方法中
public int saveChain(Chain chain) {
chain.setDate(new Date());
//chain.setId((long)44); remove this line
Boolean a;
em.persist(chain);
return 222;
}
if you assign Id, then hibernate/jpa will try to update record, which is not available, instead of inserting new record and I think will not throw exception.
如果您分配 Id,则 hibernate/jpa 将尝试更新不可用的记录,而不是插入新记录,我认为不会抛出异常。

