【发布时间】:2013-08-02 23:54:43
【问题描述】:
我无法使用 spring 和 hibernate 持久化数据。我查看了各种帖子并尝试了很多东西。但它只是行不通。 我将首先发布我的配置,然后发布我尝试的步骤。将不胜感激。
spring-jpa.xml
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" />
<context:component-scan base-package="com.gamelist.dao.classes" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
GenericDAO.java
public class GenericDaoJPA<T extends IDomainObject> implements IGenericDao<T> {
protected EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager){
this.entityManager = entityManager;
}
public void save(T object) throws DataAccessException{
entityManager.persist(object);
}
.
.
.
.
}
User.java(域)
@Entity
@Table(name = "user")
public class User implements Serializable, IDomainObject{
private long id;
private String firstName;
@Id
@GeneratedValue
public final long getId(){
return id;
}
public void setId(long id){
this.id = id;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
}
TestService.java(UserDao 实现 IUserDao 并扩展 GenericDao)
@Service(value = "testService")
@Transactional
public class TestService implements ITestService {
@Autowired
private IUserDao userDao;
@Transactional(readOnly = false)
public void saveUser(User newUser){
userDao.save(newUser);
}
.
.
.
}
persistence.xml
<persistence-unit name="gamelistPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<!--
value='create' to build a new database on each run;
value='update' to modify an existing database;
value='create-drop' means the same as 'create' but also drops tables when Hibernate closes;
value='validate' makes no changes to the database
-->
</properties>
</persistence-unit>
我没有收到任何错误或异常或任何东西。我可以从我的数据库中读取。仅更新、添加或删除不持久。
这就是我尝试过的所有内容
- 一篇文章提到将 transaction-type="RESOURCE_LOCAL" 更改为 JTA,说 RESOURCE_LOCAL 根本不存在。我认为这是如果您在使用 RESOURCE_LOCAL 时仅使用休眠而不管理事务。我相信 spring 会为您管理交易。
- 有些人提到做 em.flush 或 em.getTransaction.begin 并在使用 persist 后提交。但是每次使用上述操作时都会出现此错误。 不允许在共享 EntityManager 上创建事务
感谢任何帮助。提前致谢
【问题讨论】:
-
你能发布你的 UserDao 课程吗?
-
在使用
transaction-type="RESOURCE_LOCAL时尝试使用@PersistenceUnit,如here 所述 -
调用这一切而不是持久化的代码是什么?
标签: java spring hibernate jpa entitymanager