当我在我的服务上运行JUnit测试时,它会成功地将新实体添加到我的数据库中,但是当我从Controller调用该服务时,它不会保存到数据库中。我错过了什么?
jpa.xml
<jpa:repositories base-package="com.mypackage.commons" />
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="database" value="MYSQL" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="jdbcDataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<!-- spring based scanning for entity classes -->
<property name="packagesToScan" value="com.mypackage" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" />
<tx:annotation-driven />
UserService
@Service
public class RepositoryUserService implements UserService {
@Resource
private UserRepository userRepository;
@Transactional
@Override
public User create(User user) {
User newUser = userRepository.save(user);
return newUser;
}
}
myController的
@Controller
@Path("/users")
public class MyAPI {
@Autowired
private UserService userService;
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON)
@Transactional
public Response addUser(User newUser) {
userService.create(newUser);
}
}
答案 0 :(得分:0)
为事务设置entityManager:
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
以这种方式驱动注释:
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
尝试从控制器中删除@Transactional
,定义传播并刷新会话
@Transactional(propagation= Propagation.REQUIRED)
@Override
public User create(User user) {
try{
return userRepository.saveAndFlush(user);
} catch(DataIntegrityViolationException e){
// handle the exception in here to find out what is wrong
}
}