Spring JPA:entityManager删除不起作用

时间:2016-12-15 15:25:07

标签: java spring jpa entitymanager

我无法处理entityManager.remove()函数 当我尝试删除对象时,我没有任何错误和异常,但记录仍在数据库中。

这是我的EntityManager定义:

@Configuration
@EnableJpaRepositories
@ComponentScan("pl.lodz.p.admin")

@EnableTransactionManagement
class AdminDbConfig {     

   @Bean
   @ConfigurationProperties(prefix = "spring.datasource")
   public DataSource dataSource() {
       return DataSourceBuilder.create().build();
   }
   @Bean(name = "adminManager")
   public EntityManagerFactory entityManagerFactory() {

       HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
       vendorAdapter.setGenerateDdl(true);

       LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
       factory.setJpaVendorAdapter(vendorAdapter);
       factory.setPackagesToScan("pl.lodz.p.entities");
       factory.setDataSource(dataSource());
       factory.afterPropertiesSet();

       return factory.getObject();
   }

   @Bean
   public JpaTransactionManager transactionManager() {
       JpaTransactionManager txManager = new JpaTransactionManager();
       txManager.setEntityManagerFactory(entityManagerFactory());
       return txManager;
   }
}

服务:

@Service
@ComponentScan(basePackages = {"pl.lodz.p.admin.service"})
@Transactional(rollbackFor = AccountException.class, propagation = Propagation.REQUIRES_NEW)
public class AccountServiceImpl implements AccountService {

    @Autowired
    AccountRepository accountRepository;

    @Override
    public void deleteAccountByLogin(String login) {
        Account account = accountRepository.findByLogin(login);
        accountRepository.delete(account);
    }
}

和存储库:

@Repository("adminAccountRepository")
@Transactional(propagation = Propagation.MANDATORY)
public class AccountRepositoryImpl implements AccountRepository {
    @PersistenceContext(unitName = "adminManager")
    private EntityManager em;

    @Override
    public Account findByLogin(String login) {
        Query query = em.createNamedQuery("Account.findByLogin");
        query.setParameter("login", login);
        Account account = (Account) query.getSingleResult();
        return account;
    }

    @Override
    public void delete(Account account) {
        try {               
            em.remove(account);
        } catch (Exception e) {
            e.getCause();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

最后,我已经解决了我的问题。

在我的EntityManager配置中,我添加了

@Bean(name = "adminTransactionManager")

在我的AccountServiceImpl:

@Transactional(value = "adminTransactionManager", rollbackFor = AccountException.class, propagation = Propagation.REQUIRES_NEW)
public class AccountServiceImpl implements AccountService {

感谢。