当我尝试通过JPA(@persistanceContex)将数据插入数据库时,我遇到了一个问题
的观察 的
@Entity
public class Test {
@Id
private int id;
@Column(name="full_name")
private String fullName;
@Column(name="mobile_number")
private int mobileNumber;
.....
}
@Repository("testDAO")
@Transactional
public class TestDAO {
private EntityManager entityManager;
@PersistenceContext(unitName="CRUD_Test_Annotation")
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void save(Test test){
entityManager.persist(test);
}
}
@Service("testService")
@Transactional
public class TestService {
private static final Logger logger = LoggerFactory.getLogger(TestService.class);
@Autowired(required=true)
private TestDAO testDAO;
public void save(Test test){
logger.info("TestService::save()");
testDAO.save(test);
}
public void list(){
testDAO.getAll();
}
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(Locale locale, Model model) {
Test test = new Test();
test.setId(xx);
test.setFullName("xxxxx");
test.setMobileNumber(yyyyyy);
testService.save(test);
return "home";
}
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Declare a JPA entityManagerFactory-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
<property name="persistenceUnitName" value="CRUD_Test_Annotation" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
答案 0 :(得分:1)
首先,您不需要两个交易边界,我建议您从DAO中移除@Transactional
并将其保留在您的服务中。
首先验证spring-transaction是否已启动事务:使用调试器并在事务边界之后停止应用程序,例如在TestService.save
- 方法中。如果事务正在运行,您将在调用堆栈中看到org.springframework.transaction.interceptor.TransactionInterceptor#invoke
。如果你没有看到TransactionInterceptor,那那就是你的问题。如果交易正在运行,请发布您的persistence.xml
文件。