java CrudRepository 保存方法不返回更新的实体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25898909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:54:54  来源:igfitidea点击:

CrudRepository save method not returning updated entity

javaspringhibernatejpa

提问by Pedro Dusso

I'm working with Spring and in it spring-data-jpa:1.7.0.RELEASEand hibernate-jpa-2.1-api:1.0.0.Final. My database is a MySQL. In a integration test, when I save an entity, the entityRepository.save()method does not return a update version of it (with the auto-incremented id populated for example), thus I can see it is in the database.

我与春天和它的工作spring-data-jpa:1.7.0.RELEASEhibernate-jpa-2.1-api:1.0.0.Final。我的数据库是 MySQL。在集成测试中,当我保存一个实体时,该entityRepository.save()方法不会返回它的更新版本(例如填充了自动递增的 id),因此我可以看到它在数据库中。

Here's my configuration class:

这是我的配置类:

//@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "core.repository")
@Configuration
@PropertySource("classpath:application.properties")
public class JPAConfiguration {

    @Autowired
    private Environment env;

    private
    @Value("${db.driverClassName}")
    String driverClassName;
    private
    @Value("${db.url}")
    String url;
    private
    @Value("${db.username}")
    String user;
    private
    @Value("${db.password}")
    String password;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();

    }

    @Bean
    public DataSource dataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setDatabasePlatform(env.getProperty("hibernate.dialect"));

        final LocalContainerEntityManagerFactoryBean em =
                new LocalContainerEntityManagerFactoryBean();

        em.setJpaVendorAdapter(vendorAdapter);
        em.setPackagesToScan(new String[]{"core.persistence"});
        em.setDataSource(dataSource());
        em.afterPropertiesSet();


        return em;
    }

    @Bean
    public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
        return entityManagerFactory.createEntityManager();
    }

    @Bean
    public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
        final JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator() {
        return new HibernateExceptionTranslator();
    }
}

Here's my test class:

这是我的测试课:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JPAConfiguration.class})
//@Transactional
//@TransactionConfiguration(defaultRollback = true)
public class AgencyRepositoryIntegrationTests {

    @Autowired
    AgencyRepository agencyRepository;

    @Test
    public void testThatAgencyIsSavedIntoRepoWorks() throws Exception {

        Agency c = DomainTestData.getAgency();
        Agency d = agencyRepository.save(c);
        // here d equals to c but both have id 0.

        Collection<Agency> results = Lists.newArrayList(agencyRepository.findAll());
        //here results != null and it does contain the agency object.
        assertNotNull(results);
    }
}

I end up commenting the Transactional annotations (both in the test and in the configuration class) due to research other questions in stackoverflow, but it did not work.

由于在 stackoverflow 中研究了其他问题,我最终评论了 Transactional 注释(在测试和配置类中),但没有奏效。

Thanks

谢谢

采纳答案by Desorder

Try to uncomment your @Transactional annotation and run. I can't see any visible problem in your snippet but there is something inside me (and it's not hunger) saying that your transaction demarcation is not right. I had similar problems like this before and it was just @transaction annotations missing or transaction misconfiguration.

尝试取消注释您的 @Transactional 注释并运行。我在你的代码片段中看不到任何明显的问题,但我内心有一些东西(这不是饥饿)说你的交易划分不正确。我之前也遇到过类似的问题,只是缺少 @transaction 注释或事务配置错误。

回答by uaiHebert

Use saveAndFlush method to make sure that the entity is in the database.

使用 saveAndFlush 方法确保实体在数据库中。

Make sure to add @Transactional to your methods if a NoTransactionException appears.

如果出现 NoTransactionException,请确保将 @Transactional 添加到您的方法中。