package com.uas.search.console.b2b;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import com.uas.search.console.b2b.util.SearchConstants;

/**
 * B2B数据源的实体管理器及事务管理器配置
 * 
 * @author sunyj
 * @since 2017年4月23日 下午3:51:34
 */
@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "platformb2bEntityManagerFactory", transactionManagerRef = "platformb2bTransactionManager", basePackages = {
		"com.uas.search.console.b2b.dao" })
public class Platformb2bRepositoryConfiguration {

	@Autowired
	private JpaProperties jpaProperties;

	@Autowired
	@Qualifier(SearchConstants.PLATFORMB2B_DATASOURCE_QUALIFIER)
	private DataSource platformb2bDataSource;

	@Bean(name = "platformb2bEntityManagerFactory")
	@Primary
	public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
		return builder.dataSource(platformb2bDataSource)
				.properties(jpaProperties.getHibernateProperties(platformb2bDataSource))
				.packages("com.uas.search.console.b2b.model").persistenceUnit("platformb2bPersistenceUnit").build();
	}

	@Bean(name = "platformb2bEntityManager")
	@Primary
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactory(builder).getObject().createEntityManager();
	}

	@Bean(name = "platformb2bTransactionManager")
	@Primary
	public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactory(builder).getObject());
	}
}
