package org.jebot.config;

import com.zaxxer.hikari.HikariDataSource;
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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableJpaRepositories(basePackages = "org.jebot.repository.xxpay",
        entityManagerFactoryRef = "entityManagerFactoryBeanXxpay",
        transactionManagerRef = "platformTransactionManagerXxpay")
public class JpaXxpayConfig {


    @Autowired
    JpaProperties jpaProperties;


    @Bean
    @Qualifier(value = "dataSourceXxpay")
    @ConfigurationProperties(prefix = "spring.datasource.xxpay")
    DataSource dataSourceXxpay() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBeanXxpay(
            EntityManagerFactoryBuilder builder) {
        Map<String, String> properties = jpaProperties.getProperties();
        properties.put("hibernate.hbm2ddl.auto", "none");
        return builder.dataSource(dataSourceXxpay()) //配置数据源
                .properties(jpaProperties.getProperties())//设置 JPA 相关配置
                .packages("org.jebot.models.xxpay")//设置实体类所在的位置
                .persistenceUnit("xxpay")//配置持久化单元名。若项目中只有一个 EntityManagerFactory，则 persistenceUnit 可以省略掉，若有多个，则必须明确指定持久化单元名。
                .build();
    }


    @Bean
    PlatformTransactionManager platformTransactionManagerXxpay(
            EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryBeanXxpay(builder).getObject());
    }

}
