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 org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "org.jebot.repository.jebot",
        entityManagerFactoryRef = "entityManagerFactoryBeanJebot",
        transactionManagerRef = "platformTransactionManagerJebot")
public class JpaJebotConfig {


    @Autowired
    JpaProperties jpaProperties;

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

    @Bean
    @Primary
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBeanJebot(
            EntityManagerFactoryBuilder builder) {
        return builder.dataSource(dataSourceJebot()) //配置数据源
                .properties(jpaProperties.getProperties())
                .packages("org.jebot.models.jebot")
                .persistenceUnit("jebot")
                .build();
    }

    @Bean
    @Primary
    PlatformTransactionManager platformTransactionManagerJebot(
            EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryBeanJebot(builder).getObject());
    }

}
