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.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;

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

	@Autowired
	private JpaProperties jpaProperties;

	@Autowired
	@Qualifier(SearchConstants.PLATFORMMANAGER_DATASOURCE_QUALIFIER)
	private DataSource platformmanagerDataSource;

	@Bean(name = "platformmanagerEntityManagerFactory")
	public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
		return builder.dataSource(platformmanagerDataSource)
				.properties(jpaProperties.getHibernateProperties(platformmanagerDataSource))
				.packages("com.uas.search.console.b2b.platformmanager.model")
				.persistenceUnit("platformmanagerPersistenceUnit").build();
	}

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

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