java 如何以编程方式配置 TransactionManager

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12971007/
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-10-31 11:00:29  来源:igfitidea点击:

How to configure TransactionManager programmatically

javahibernatespring-mvcspring-transactions

提问by dwalldorf

I'm having an application here based on Spring MVC. My workmate (btw he's not here) configured it programmatically and everything seems to work, except for the TransactionManager. I have never configured a Spring web application like this and I have no clue what to do and also can not find any documentation about how to configure a webapplication like this.

我在这里有一个基于 Spring MVC 的应用程序。我的同事(顺便说一句,他不在这里)以编程方式对其进行了配置,除了 TransactionManager 之外,一切似乎都可以正常工作。我从来没有像这样配置过 Spring Web 应用程序,我不知道该怎么做,也找不到任何关于如何配置这样的 Web 应用程序的文档。

I'll just show you the 'AppInitializer' and the 'EntityManagerConfig'.

我只会向您展示“AppInitializer”和“EntityManagerConfig”。

AppInitializer:

应用初始化器:

public class AppInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext context;
    ServletRegistration.Dynamic dispatcherServletRegistration;
    FilterRegistration.Dynamic encodingFilterRegistration, compressionFilterRegistration;
    Set<SessionTrackingMode> sessionTrackingModes = new HashSet<SessionTrackingMode>();

    sessionTrackingModes.add(SessionTrackingMode.SSL);

    context = new AnnotationConfigWebApplicationContext();
    context.setServletContext(servletContext);
    context.scan("de.devbliss.doc");

    servletContext.addListener(new ContextLoaderListener(context));
    servletContext.addListener(new Log4jConfigListener());

    dispatcherServletRegistration = servletContext.addServlet("main", new DispatcherServlet(context));
    dispatcherServletRegistration.setLoadOnStartup(1);
    dispatcherServletRegistration.addMapping("/*");

    encodingFilterRegistration = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
    encodingFilterRegistration.setInitParameter("encoding", "UTF-8");
    encodingFilterRegistration.setInitParameter("forceEncoding", "true");
    encodingFilterRegistration.addMappingForUrlPatterns(null, false, "/*");

    compressionFilterRegistration = servletContext.addFilter("compressionFilter", GzipFilter.class);
    compressionFilterRegistration.addMappingForUrlPatterns(null, false, "/*");

    compressionFilterRegistration = servletContext.addFilter("springSecurityFilterChain",
            DelegatingFilterProxy.class);
    compressionFilterRegistration.addMappingForUrlPatterns(null, false, "/*");

    servletContext.setSessionTrackingModes(sessionTrackingModes);
}
}

EntityManagerConfig:

实体管理器配置:

@Configuration
@PropertySource("classpath:/db.properties")
public class EntityManagerConfig {

@Bean
public DataSource dataSource(Environment env) {
    BasicDataSource ds = new BasicDataSource();

    ds.setUrl(env.getProperty("url", "localhost"));
    ds.setUsername(env.getProperty("user", "blissdoc"));
    ds.setPassword(env.getProperty("password", "s3cret"));

    return ds;
}

@Bean
@Inject
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
    LocalSessionFactoryBean factory = new LocalSessionFactoryBean();

    factory.setDataSource(dataSource);

    return factory;
}

@Bean
public HibernateTransactionManager transactionManager(
        SessionFactory sessionFactory) {
    HibernateTransactionManager tm = new HibernateTransactionManager(
            sessionFactory);
    return tm;
}

@SuppressWarnings("unchecked")
@Bean
@Inject
public LocalContainerEntityManagerFactoryBean entityManager(
        DataSource dataSource, AbstractEnvironment env) {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
    HibernateJpaDialect jpaDialect = new HibernateJpaDialect();
    org.springframework.core.env.PropertySource<?> source;
    Iterator<org.springframework.core.env.PropertySource<?>> sources;

    // jpaVendorAdapter.setDatabase(Database.MYSQL);

    jpaVendorAdapter.setGenerateDdl(true);
    jpaVendorAdapter.setShowSql(true);

    Properties jpaProperties = new Properties();

    sources = env.getPropertySources().iterator();
    while (sources.hasNext()) {
        source = sources.next();
        if (source.getSource() instanceof Map) {
            for (Map.Entry<String, String> property : ((Map<String, String>) source
                    .getSource()).entrySet()) {
                jpaProperties.put(property.getKey(), property.getValue());
            }
        }
    }

    em.setJpaProperties(jpaProperties);

    em.setDataSource(dataSource);
    em.setPersistenceUnitName("blissdoc-unit");
    em.setPackagesToScan("de.devbliss.doc.model");
    em.setJpaDialect(jpaDialect);
    em.setJpaVendorAdapter(jpaVendorAdapter);

    return em;
}

// @Bean
// @Inject
// public JpaTransactionManager jpaTransactionManager(
// EntityManagerFactory entityManagerFactory) {
// JpaTransactionManager tm = new JpaTransactionManager(
// entityManagerFactory);
// return tm;
// }

@Bean
@Inject
public JpaRepositoryFactory jpaRepositoryFactory(
        EntityManagerFactory entityManagerFactory) {
    JpaRepositoryFactory factory = new JpaRepositoryFactory(
            entityManagerFactory.createEntityManager());
    return factory;
}

@Bean
@Inject
public UserRepository userRepository(
        JpaRepositoryFactory jpaRepositoryFactory) {
    return jpaRepositoryFactory.getRepository(UserRepository.class);
}

@Bean
@Inject
public ProjectRepository projectRepository(
        JpaRepositoryFactory jpaRepositoryFactory) {
    return jpaRepositoryFactory.getRepository(ProjectRepository.class);
}
}

--- Update PersistenceJPAConfig (former EntityManagerConfig):

--- 更新 PersistenceJPAConfig(原 EntityManagerConfig):

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:/db.properties")
public class PersistenceJPAConfig {

@Inject
private Environment env;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setDataSource(dataSource());
    factoryBean.setPackagesToScan(new String[] { "de.devbliss.doc" });
    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter() {
        {
            // JPA properties
        }
    };
    factoryBean.setJpaVendorAdapter(vendorAdapter);

    return factoryBean;
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUrl(env.getProperty("url", "localhost"));
    dataSource.setUsername(env.getProperty("user", "blissdoc"));
    dataSource.setPassword(env.getProperty("password", "s3cret"));
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactoryBean()
            .getObject());

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}
}

回答by axtavt

@Configuration-specific counterparts of custom XML elements such as <tx:annotation-driven>are @Enable...annotations.

@Configuration自定义XML元素的特异性同行诸如<tx:annotation-driven>@Enable...注解。

In order to enable support for @Transactionalyou need to annotate your @Configurationclass with @EnableTransactionManagement:

为了启用对@Transactional您的支持,您需要使用以下内容注释您的@Configuration@EnableTransactionManagement

@Configuration 
@PropertySource("classpath:/db.properties") 
@EnableTransactionManagement
public class EntityManagerConfig { ... }

See also:

也可以看看:

回答by jelies

Have you tried to extend from TransactionManagementConfigurer?

你试过从 扩展TransactionManagementConfigurer吗?

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:/db.properties")
public class EntityManagerConfig implements TransactionManagementConfigurer {

    ...

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return transactionManager();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager(entityManagerFactory());
        transactionManager.setDataSource(dataSource);
        transactionManager.setJpaDialect(new HibernateJpaDialect());
        return transactionManager;
    }

    ...
}

And seems like you are using Spring Data JPA, so I recommend you to use also @EnableJpaRepositories("com.your.repositories.package")to automatically configure your Spring Data Repositories.

似乎您正在使用 Spring Data JPA,所以我建议您也使用它@EnableJpaRepositories("com.your.repositories.package")来自动配置您的 Spring Data Repositories。

Hope this helps :)

希望这可以帮助 :)