hibernate persist()不会保存数据,但save()会保存数据

时间:2015-09-28 19:46:10

标签: hibernate

我有测试:

    @Transactional(propagation=Propagation.REQUIRES_NEW)
    @Test
    @ExpectedDatabase(
            value = "classpath:ExpectedAddedDonation.xml",
            assertionMode = DatabaseAssertionMode.NON_STRICT
            )
    public void testAddDonations() throws MalformedURLException, SQLException, DatabaseUnitException {
        prepareCategoriesAndProjects();
        Project proj = (Project) session.get(Project.class, 1);
        Project proj2 = (Project) session.get(Project.class, 2);
        DonationLogic donation = new DonationLogic(10000,50);
        donation.setProject(proj);
        DonationLogic donation2 = new DonationLogic(100000,500);
        donation2.setProject(proj2);

        System.out.println(donation.getProject().getName() + "---" + donation.getCollectAmount() + "---" + donation.getDaysLeft() + "---" + donation.getTotalAmount());
//      session.flush();
        session.persist(donation);
        session.persist(donation2);

    }

    private void prepareCategoriesAndProjects() throws MalformedURLException, DataSetException, SQLException, DatabaseUnitException {
        IDataSet dataSet = new FlatXmlDataSetBuilder().build(new File(
                "./src/test/resources/sampleDataForShow.xml"
                ));
        IDatabaseConnection dbConn = new DatabaseDataSourceConnection(dataSource);
        DatabaseOperation.CLEAN_INSERT.execute(dbConn, dataSet);
    }

测试检查是否有两行添加到捐赠表中。仅当我将persist()更改为save()时,测试才会成功。我不明白为什么persist()不起作用? Hibernate不会生成INSERT查询。

1 个答案:

答案 0 :(得分:0)

保证在flush操作后发出查询。所有其他事情都可以推迟。实际上与save相同。 Here可以找到更多信息。