美文网首页
springboot中使用hibernate

springboot中使用hibernate

作者: guideEmotion | 来源:发表于2019-09-27 21:47 被阅读0次

一 简单实现

我们用springboot集成jpa后,jpa默认是用hibernate作为实现框架。所以我只需要如下,就可以创建SessionFactory.

       @Autowired
      private EntityManagerFactory entityManagerFactory;


    @Primary
    @Bean("sessionFactory")
    public SessionFactory sessionFactory() {
        if (factory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("factory is not a hibernate factory");
        }
        return factory.unwrap(SessionFactory.class);
    }
    
//  @Primary
//  @Bean(name = "sessionFactory")
//  public LocalSessionFactoryBean localSessionFactoryBean() throws IOException {
//      LocalSessionFactoryBean bean=new LocalSessionFactoryBean();
//      bean.setDataSource(dynamicDataSource());
//      bean.setPackagesToScan(config.getPackagesToScan());
//      bean.setHibernateProperties(prop);
//      bean.afterPropertiesSet();
//      return bean;
//  }
    
    @Bean
    public HibernateTransactionManager txManager(SessionFactory sessionFactory) throws Exception {
        HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
        hibernateTransactionManager.setSessionFactory(sessionFactory);
        return hibernateTransactionManager;
    }

注意
spring data jpa默认已经往我们的spring容器中注入了一个EntityManagerFactory

二 全部自定义

主要类

@Configuration
public class DynamicJpaConfig extends BaseJpaConfig {
    @Autowired
    private DataSourceConfig config;
    
    @Bean
    @Primary
    public DynamicDataSource dynamicDataSource() {
        Map<Object, Object> targetDataSources = new HashMap<>();
        Map<String, HikariConfig> slaves = config.getSlaves();
        if (slaves != null) {
            Iterator<String> iter = slaves.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                targetDataSources.put(key, new HikariDataSource(slaves.get(key)));
                DynamicDataSourceContextHolder.dataSourceIds.add(key);
            }
        }
        DynamicDataSource dataSource = new DynamicDataSource();
        // 设置数据源映射
        dataSource.setTargetDataSources(targetDataSources);
        // 设置默认数据源,当无法映射到数据源时会使用默认数据源
        dataSource.setDefaultTargetDataSource(new HikariDataSource(config.getMaster()));
        dataSource.afterPropertiesSet();
        return dataSource;
    }

    @Primary
    @Bean("jdbcTemplate")
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dynamicDataSource());
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dynamicDataSource());
        factory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        factory.setPackagesToScan(config.getPackagesToScan());
        factory.setJpaProperties(prop);
        factory.afterPropertiesSet();
        return factory;
    }

    @Primary
    @Bean("sessionFactory")
    public SessionFactory sessionFactory() {
        EntityManagerFactory factory = entityManagerFactory().getNativeEntityManagerFactory();
        if (factory.unwrap(SessionFactory.class) == null) {
            throw new NullPointerException("factory is not a hibernate factory");
        }
        return factory.unwrap(SessionFactory.class);
    }
    
//  @Primary
//  @Bean(name = "sessionFactory")
//  public LocalSessionFactoryBean localSessionFactoryBean() throws IOException {
//      LocalSessionFactoryBean bean=new LocalSessionFactoryBean();
//      bean.setDataSource(dynamicDataSource());
//      bean.setPackagesToScan(config.getPackagesToScan());
//      bean.setHibernateProperties(prop);
//      bean.afterPropertiesSet();
//      return bean;
//  }
    
    @Bean
    public HibernateTransactionManager txManager(SessionFactory sessionFactory) throws Exception {
        HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
        hibernateTransactionManager.setSessionFactory(sessionFactory);
        return hibernateTransactionManager;
    }

}

jpaProperties

public class BaseJpaConfig {
    protected static final Properties prop = new Properties();
    static {
        InputStream in = BaseJpaConfig.class.getResourceAsStream("/hibernate.properties");
        try {
            prop.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Resource
    protected Environment env;

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

}

相关文章

网友评论

      本文标题:springboot中使用hibernate

      本文链接:https://www.haomeiwen.com/subject/sjfusctx.html