我在使用hibernate时遇到了一些麻烦。 EntityManager.merge()没有任何效果,也没有persist()。
我的代码:
@Stateless
public class UserManager {
@Inject
private EntityManager em;
public User save(User user){
return em.merge(user);
}
}
用户实体非常简单:
@Entity
public class User implements Serializable {
private static final long serialVersionUID = -6249050000984099316L;
@Id
@GeneratedValue
private Long id;
private String name;
//some more fields
//...
// getters / setters following
//...
}
我的ManagedBean只是调用userManager.save(user)
并传递用户对象。
我的数据库中的用户表是完全空的,所以我希望merge()
导致INSERT语句。
表User上既没有插入也没有更新。
只更新生成的ID的next_val:
INFO [stdout] (http-localhost-127.0.0.1-8082-7) Hibernate: select next_val as id_val from hibernate_sequence for update
INFO [stdout] (http-localhost-127.0.0.1-8082-7) Hibernate: update hibernate_sequence set next_val= ? where next_val=?
请帮帮我。提前谢谢。
编辑:
EntityManager Producer:
public class Resources {
@PersistenceContext
private EntityManager em;
@Produces
public EntityManager produceEntityManager()
{
return em;
}
}
的persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">
<jta-data-source>java:jboss/datasources/dkmgr</jta-data-source>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.import_files_sql_extractor"
value="org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor" />
<property name="hibernate.hbm2ddl.import_files" value="import.sql" />
</properties>
</persistence-unit>
</persistence>
答案 0 :(得分:2)
如果你正在使用EJB,那么你应该试试这个:
public User save(User user){
em.getTransaction().begin();
em.merge(user);
em.getTransaction().commit();
return user;
}