我正在尝试让用户使用Spring事务支持休眠。我已经将会话工厂配置为bean(参见下文)并创建了一个DAO类。我还使用了Spring测试支持-运行带有@Transactional批注的测试类,我理解)应该允许我在单个事务中调用多个dao操作。我读到休眠应该在提交之后或执行选择之前刷新其持久性上下文。我希望后者休眠。但是我的大多数测试都失败了,因为(根据日志)休眠在插入之后和选择之前没有刷新其持久性上下文。

这是弹簧配置的弹簧部分:

@Configuration
@PropertySource("/db.properties")
@EnableTransactionManagement
@ComponentScan(basePackages = "repository")
public class DataAccessConfiguration {

 @Bean
    public SessionFactory sessionFactory() throws IOException {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(pool());
        sessionFactoryBean.setPackagesToScan("domain");
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        sessionFactoryBean.afterPropertiesSet();
        return sessionFactoryBean.getObject();
    }

    private Properties hibernateProperties() {
        Properties hibernateProp = new Properties();
        hibernateProp.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        hibernateProp.put("hibernate.format_sql", true);
        hibernateProp.put("hibernate.use_sql_comments", true);
        hibernateProp.put("hibernate.show_sql", true);
        hibernateProp.put("hibernate.max_fetch_depth", 3);
        hibernateProp.put("hibernate.jdbc.batch_size", 10);
        hibernateProp.put("hibernate.jdbc.fetch_size", 50);
        hibernateProp.put("hibernate.hbm2ddl.auto", "update");
        return hibernateProp;
    }

    @Bean
    @Profile("hibernate")
    public PlatformTransactionManager transactionManager() throws IOException {
        HibernateTransactionManager manager = new HibernateTransactionManager(sessionFactory());
        manager.setDataSource(pool());

        return manager;
    }

    @Bean
    @Profile("jdbc")
    PlatformTransactionManager jdbcTransactionManager(){
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(pool());

        return manager;
    }
}


我正在使用两个平台事务管理器-一个用于jdbc,另一个用于hibernate。我尝试删除jdbc管理器,仅保留hibernate(无法正常工作)。

这是dao类:

@Repository
@Profile("hibernate")
public class UserDaoHibernate implements UserDao {

    private final SessionFactory sessionFactory;

    public UserDaoHibernate(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void insert(User user) {
        sessionFactory.getCurrentSession().save(user);
    }

    @Override
    public void addRole(User user, Role role) {
        NativeQuery addRoleQuery = sessionFactory.getCurrentSession()
                .createNativeQuery("INSERT INTO roles(user_name, user_role) VALUES(:user_name,:user_role)");
        addRoleQuery.setParameter("user_name",user.getUsername());
        addRoleQuery.setParameter("user_role", role.toString().toUpperCase());
        addRoleQuery.executeUpdate();
    }

    @Override
    public boolean hasRole(User user, Role role) {
        NativeQuery hasRoleQuery = sessionFactory.getCurrentSession()
                .createSQLQuery("SELECT * FROM roles WHERE user_name = :user_name AND user_role = :user_role");
        hasRoleQuery.setParameter("user_name", user.getUsername());
        hasRoleQuery.setParameter("user_role", role.toString().toUpperCase());
        return hasRoleQuery.getResultList().size() == 1;
    }

}


在测试类中失败的测试代码在这里:

@ContextConfiguration(classes = {DataAccessConfiguration.class})
@Rollback
@ExtendWith(SpringExtension.class)
@ActiveProfiles("hibernate")
@Transactional
public class UserDaoTest {

    @Autowired
    private UserDao sut;

    private User user = new User("NEW_USERNAME123", "NEW_PASSWORD123", LocalDate.now().minusYears(20),
            "FIRST_NAME", "LAST_NAME");

    @Test
    public void shouldAddNewRoleToUser(){
        sut.insert(user);
        assertFalse(sut.hasRole(user,Role.MEMBER));

        sut.addRole(user, Role.MEMBER);

        assertTrue(sut.hasRole(user,Role.MEMBER));
    }

}


这是运行测试方法后的输出(不包括事务注释):

Hibernate:
    select
        nextval ('USER_ID_SEQUENCE')
Hibernate:
    /* dynamic native SQL query */ SELECT
        *
    FROM
        roles
    WHERE
        user_name = ?
        AND user_role = ?
Hibernate:
    /* dynamic native SQL query */ INSERT
    INTO
        roles
        (user_name, user_role)
    VALUES
        (?,?)
Nov 13, 2019 3:05:31 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 23503
Nov 13, 2019 3:05:31 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: insert or update on table "roles" violates foreign key constraint "fk_roles_user_id"
  Detail: Key (user_name)=(NEW_USERNAME123) is not present in table "users_table".


当我以编程方式提交会话时
sessionFactory.getCurrentSession()。getTransaction()。commit();在插入结束时,一切正常。

最佳答案

尝试使用插入方法@Transactional或使用sessionFactory.getCurrentSession()。flush()

07-24 18:39