import jakarta.persistence.EntityManagerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.HashMap; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; @Configuration @EnableJpaRepositories( basePackages = "com.template.plex.repository.sqlite", entityManagerFactoryRef = "sqliteEntityManagerFactory", transactionManagerRef = "sqliteTransactionManager" ) public class SqliteConfig { @Bean(name = "sqliteDataSource") public DataSource sqliteDataSource(ResourceLoader resourceLoader, @Value("${spring.datasource.sqlite.dbName}") String dbFileName) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.sqlite.JDBC"); String resourcePath = "classpath:db/sqlite/" + dbFileName; Resource sqliteResource = resourceLoader.getResource(resourcePath); if (!sqliteResource.exists()) { throw new IllegalArgumentException("SQLite DB file " + dbFileName + " not found in resources (expected at " + resourcePath + ")"); } File tempDbFile; try { tempDbFile = File.createTempFile("sqlite-migration-", ".db"); Files.copy(sqliteResource.getInputStream(), tempDbFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RuntimeException("Failed to create temporary SQLite DB file", e); } dataSource.setUrl("jdbc:sqlite:" + tempDbFile.getAbsolutePath()); return dataSource; } @Bean(name = "sqliteEntityManagerFactory") public LocalContainerEntityManagerFactoryBean sqliteEntityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("sqliteDataSource") DataSource dataSource) { HashMap jpaProps = new HashMap<>(); jpaProps.put("hibernate.hbm2ddl.auto", "none"); jpaProps.put("hibernate.default_schema", ""); jpaProps.put("hibernate.dialect", "org.hibernate.community.dialect.SQLiteDialect"); return builder .dataSource(dataSource) .packages("com.template.plex.model.external") .persistenceUnit("sqlite") .properties(jpaProps) .build(); } @Bean(name = {"sqliteTransactionManager", "transactionManager"}) public PlatformTransactionManager sqliteTransactionManager( @Qualifier("sqliteEntityManagerFactory") EntityManagerFactory emf) { return new JpaTransactionManager(emf); } }