Spring Boot Multiple Datasource

Sono abbastanza nuovo per l’avvio di spring e mi piacerebbe creare una fonte dati multipla per il mio progetto. Ecco il mio caso attuale. Ho due pacchetti per entity framework per database multipli. Diciamo

com.test.entity.db.mysql ; for entities that belong to MySql com.test.entity.db.h2 ; for entities that belong to H2 Databases 

Quindi, attualmente ho due classi di quadro

UserMySql.java

 @Entity @Table(name="usermysql") public class UserMysql{ @Id @GeneratedValue public int id; public String name; } 

UserH2.java

 @Entity @Table(name="userh2") public class Userh2 { @Id @GeneratedValue public int id; public String name; } 

Mi piacerebbe realizzare una configurazione in cui se creo l’utente da UserMySql, verrà salvato nel database MySql e se creo l’utente da Userh2 verrà salvato in H2 Database. Quindi, ho anche due DBConfig, diciamo MySqlDbConfig e H2DbConfig.

(com.test.model è un pacchetto in cui inserirò la mia class di repository. Sarà definita di seguito)

MySqlDbConfig.java

 @Configuration @EnableJpaRepositories( basePackages="com.test.model", entityManagerFactoryRef = "mysqlEntityManager") public class MySqlDBConfig { @Bean @Primary @ConfigurationProperties(prefix="datasource.test.mysql") public DataSource mysqlDataSource(){ return DataSourceBuilder .create() .build(); } @Bean(name="mysqlEntityManager") public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory( EntityManagerFactoryBuilder builder){ return builder.dataSource(mysqlDataSource()) .packages("com.test.entity.db.mysql") .build(); } } 

H2DbConfig.java

 @Configuration @EnableJpaRepositories( entityManagerFactoryRef = "h2EntityManager") public class H2DbConfig { @Bean @ConfigurationProperties(prefix="datasource.test.h2") public DataSource h2DataSource(){ return DataSourceBuilder .create() .driverClassName("org.h2.Driver") .build(); } @Bean(name="h2EntityManager") public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory( EntityManagerFactoryBuilder builder){ return builder.dataSource(h2DataSource()) .packages("com.test.entity.db.h2") .build(); } } 

Il mio file application.properties

 #DataSource settings for mysql datasource.test.mysql.jdbcUrl = jdbc:mysql://127.0.0.1:3306/test datasource.test.mysql.username = root datasource.test.mysql.password = root datasource.test.mysql.driverClassName = com.mysql.jdbc.Driver #DataSource settings for H2 datasource.test.h2.jdbcUrl = jdbc:h2:~/test datasource.test.h2.username = sa # DataSource settings: set here configurations for the database connection spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test spring.datasource.username = root spring.datasource.password = root spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.validation-query=SELECT 1 # Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate settings are prefixed with spring.jpa.hibernate.* spring.jpa.hibernate.ddl-auto = update spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.hibernate.show_sql = true spring.jpa.hibernate.format_sql = true server.port=8080 endpoints.shutdown.enabled=false 

E poi per crud ho UserMySqlDao e UserH2Dao

UserMySqlDao.java

 @Transactional @Repository public interface UserMysqlDao extends CrudRepository{ public UserMysql findByName(String name); } 

UserH2Dao.java

 @Transactional @Repositories public interface UserH2Dao extends CrudRepository{ public Userh2 findByName(String name); } 

E per ultimo, ho un UserController come endpoint per accedere al mio servizio

UserController.java

 @Controller @RequestMapping("/user") public class UserController { @Autowired private UserMysqlDao userMysqlDao; @Autowired private UserH2Dao userH2Dao; @RequestMapping("/createM") @ResponseBody public String createUserMySql(String name){ UserMysql user = new UserMysql(); try{ user.name = name; userMysqlDao.save(user); return "Success creating user with Id: "+user.id; }catch(Exception ex){ return "Error creating the user: " + ex.toString(); } } @RequestMapping("/createH") @ResponseBody public String createUserH2(String name){ Userh2 user = new Userh2(); try{ user.name = name; userH2Dao.save(user); return "Success creating user with Id: "+user.id; }catch(Exception ex){ return "Error creating the user: " + ex.toString(); } } } 

Application.java

 @Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) @EntityScan(basePackages="com.test.entity.db") @ComponentScan public class Application { public static void main(String[] args) { System.out.println("Entering spring boot"); ApplicationContext ctx = SpringApplication.run(Application.class, args); System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.print(beanName); System.out.print(" "); } System.out.println(""); } } 

Con questa configurazione il mio avvio Spring funziona bene, ma quando accedo

 http://localhost/user/createM?name=myname it writes an exception Error creating the user: org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement 

Ho cercato su google e non ho ancora trovato una soluzione. Qualche idea sul perché questa eccezione si verifica? Ed è questo il modo migliore per implementare più origini dati per implementare il mio caso sopra? Sono aperto a refactoring completo se necessario.

Grazie

Penso che tu possa trovarlo utile

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources

Mostra come definire più origini dati e assegnarne una come primaria.

Ecco un esempio piuttosto completo, contiene anche le transazioni di distribuzione – se ne hai bisogno.

http://fabiomaffioletti.me/blog/2014/04/15/distributed-transactions-multiple-databases-spring-boot-spring-data-jpa-atomikos/

Quello di cui hai bisogno è creare 2 classi di configurazione, separare i pacchetti modello / repository ecc. Per rendere la configurazione facile.

Inoltre, nell’esempio sopra, crea manualmente le origini dati. Puoi evitarlo usando il metodo su spring doc, con l’annotazione @ConfigurationProperties. Ecco un esempio di questo:

http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html

Spero che questi aiuti.

Ho affrontato lo stesso problema qualche giorno fa, ho seguito il link indicato di seguito e ho potuto risolvere il problema

http://www.baeldung.com/spring-data-jpa-multiple-databases

Ho risolto il problema (Come connettere più database usando Spring e Hibernate) in questo modo, spero che possa aiutare 🙂

NOTA: Ho aggiunto il codice pertinente, gentilmente faccio il dao con l’aiuto di impl che ho usato nel codice qui sotto menzionato.

web.xml

   MultipleDatabaseConnectivityInSpring  index.jsp   dispatcher org.springframework.web.servlet.DispatcherServlet 1   org.springframework.web.context.ContextLoaderListener   contextConfigLocation  /WEB-INF/dispatcher-servlet.xml    dispatcher *.htm   30   

persistence.xml

    org.hibernate.ejb.HibernatePersistence in.india.entities.CustomerDetails              org.hibernate.ejb.HibernatePersistence in.india.entities.CompanyDetails              

dispatcher-servlet

           /WEB-INF/jsp/   .jsp                            

class java per persistere in un unico database

 package in.india.service.dao.impl; import in.india.entities.CompanyDetails; import in.india.service.CompanyService; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.transaction.annotation.Transactional; public class CompanyServiceImpl implements CompanyService { @PersistenceContext(unitName = "entityManagerFactoryTwo") EntityManager entityManager; @Transactional("manager2") @Override public boolean companyService(CompanyDetails companyDetails) { boolean flag = false; try { entityManager.persist(companyDetails); flag = true; } catch (Exception e) { flag = false; } return flag; } } 

class java per persistere in un altro database

 package in.india.service.dao.impl; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.transaction.annotation.Transactional; import in.india.entities.CustomerDetails; import in.india.service.CustomerService; public class CustomerServiceImpl implements CustomerService { @PersistenceContext(unitName = "localPersistenceUnitOne") EntityManager entityManager; @Override @Transactional(value = "manager1") public boolean customerService(CustomerDetails companyData) { boolean flag = false; entityManager.persist(companyData); return flag; } } 

customer.jsp

 <%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>     Insert title here   

SpringWithMultipleDatabase's

First Name
Last Name
Email Id
Profession
Address
Age

company.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>     ScheduleJobs   

SpringWithMultipleDatabase's

Company Name
Company Strength
Company Location

index.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>     Home   

Multiple Database Connectivity In Spring sdfsdsd

Click here to go on Customer page
Click here to go on Company page

success.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>     ScheduleJobs   

SpringWithMultipleDatabase

Successfully Saved

CompanyController

 package in.india.controller; import in.india.bean.CompanyBean; import in.india.entities.CompanyDetails; import in.india.service.CompanyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class CompanyController { @Autowired CompanyService companyService; @RequestMapping(value = "/https://stackoverflow.com/questions/27614301/spring-boot-multiple-datasource/companyRequest.htm", method = RequestMethod.GET) public ModelAndView addStudent(ModelMap model) { CompanyBean companyBean = new CompanyBean(); model.addAttribute(companyBean); return new ModelAndView("company"); } @RequestMapping(value = "/addCompany.htm", method = RequestMethod.GET) public ModelAndView companyController(@ModelAttribute("companyBean") CompanyBean companyBean, Model model) { CompanyDetails companyDetails = new CompanyDetails(); companyDetails.setCompanyLocation(companyBean.getCompanyLocation()); companyDetails.setCompanyName(companyBean.getCompanyName()); companyDetails.setCompanyStrength(companyBean.getCompanyStrength()); companyService.companyService(companyDetails); return new ModelAndView("success"); } } 

CustomerController

 package in.india.controller; import in.india.bean.CustomerBean; import in.india.entities.CustomerDetails; import in.india.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class CustomerController { @Autowired CustomerService customerService; @RequestMapping(value = "/https://stackoverflow.com/questions/27614301/spring-boot-multiple-datasource/customerRequest.htm", method = RequestMethod.GET) public ModelAndView addStudent(ModelMap model) { CustomerBean customerBean = new CustomerBean(); model.addAttribute(customerBean); return new ModelAndView("customer"); } @RequestMapping(value = "/addCustomer.htm", method = RequestMethod.GET) public ModelAndView customerController(@ModelAttribute("customerBean") CustomerBean customer, Model model) { CustomerDetails customerDetails = new CustomerDetails(); customerDetails.setAddress(customer.getAddress()); customerDetails.setAge(customer.getAge()); customerDetails.setEmailId(customer.getEmailId()); customerDetails.setFirstName(customer.getFirstName()); customerDetails.setLastName(customer.getLastName()); customerDetails.setProfession(customer.getProfession()); customerService.customerService(customerDetails); return new ModelAndView("success"); } } 

CompanyDetails Entity

 package in.india.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "company_details") public class CompanyDetails { @Id @SequenceGenerator(name = "company_details_seq", sequenceName = "company_details_seq", initialValue = 1, allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "company_details_seq") @Column(name = "company_details_id") private Long companyDetailsId; @Column(name = "company_name") private String companyName; @Column(name = "company_strength") private Long companyStrength; @Column(name = "company_location") private String companyLocation; public Long getCompanyDetailsId() { return companyDetailsId; } public void setCompanyDetailsId(Long companyDetailsId) { this.companyDetailsId = companyDetailsId; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public Long getCompanyStrength() { return companyStrength; } public void setCompanyStrength(Long companyStrength) { this.companyStrength = companyStrength; } public String getCompanyLocation() { return companyLocation; } public void setCompanyLocation(String companyLocation) { this.companyLocation = companyLocation; } } 

Entità CustomerDetails

 package in.india.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "customer_details") public class CustomerDetails { @Id @SequenceGenerator(name = "customer_details_seq", sequenceName = "customer_details_seq", initialValue = 1, allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_details_seq") @Column(name = "customer_details_id") private Long customerDetailsId; @Column(name = "first_name ") private String firstName; @Column(name = "last_name ") private String lastName; @Column(name = "email_id") private String emailId; @Column(name = "profession") private String profession; @Column(name = "address") private String address; @Column(name = "age") private int age; public Long getCustomerDetailsId() { return customerDetailsId; } public void setCustomerDetailsId(Long customerDetailsId) { this.customerDetailsId = customerDetailsId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getProfession() { return profession; } public void setProfession(String profession) { this.profession = profession; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } 

C’è un esempio con due database, il database è mysql e orm è mybatis.Ecco può aiutarti.

https://github.com/jinjunzhu/spring-boot-mybatis.git

Utilizzare più origini dati o realizzare la separazione tra lettura e scrittura. è necessario avere una conoscenza di Class AbstractRoutingDataSource che supporta l’origine dati dynamic scelta.

Ecco il mio datasource.yaml e ho capito come risolvere questo caso. Puoi riferirti a questo progetto spring-boot + quarzo . Spero che questo ti possa aiutare.

 dbServer: default: localhost:3306 read: localhost:3306 write: localhost:3306 datasource: default: type: com.zaxxer.hikari.HikariDataSource pool-name: default continue-on-error: false jdbc-url: jdbc:mysql://${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8 username: root password: lh1234 connection-timeout: 30000 connection-test-query: SELECT 1 maximum-pool-size: 5 minimum-idle: 2 idle-timeout: 600000 destroy-method: shutdown auto-commit: false read: type: com.zaxxer.hikari.HikariDataSource pool-name: read continue-on-error: false jdbc-url: jdbc:mysql://${dbServer.read}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8 username: root password: lh1234 connection-timeout: 30000 connection-test-query: SELECT 1 maximum-pool-size: 5 minimum-idle: 2 idle-timeout: 600000 destroy-method: shutdown auto-commit: false write: type: com.zaxxer.hikari.HikariDataSource pool-name: write continue-on-error: false jdbc-url: jdbc:mysql://${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8 username: root password: lh1234 connection-timeout: 30000 connection-test-query: SELECT 1 maximum-pool-size: 5 minimum-idle: 2 idle-timeout: 600000 destroy-method: shutdown auto-commit: false 

Utilizzando due origini dati è necessario il proprio gestore delle transazioni.

 @Configuration public class MySqlDBConfig { @Bean @Primary @ConfigurationProperties(prefix="datasource.test.mysql") public DataSource mysqlDataSource(){ return DataSourceBuilder .create() .build(); } @Bean("mysqlTx") public DataSourceTransactionManager mysqlTx() { return new DataSourceTransactionManager(mysqlDataSource()); } // same for another DS } 

E poi usalo di conseguenza in @Transaction

 @Transactional("mysqlTx") @Repository public interface UserMysqlDao extends CrudRepository{ public UserMysql findByName(String name); } 

Grazie a tutti per il vostro aiuto, ma non è complicato come sembra; quasi tutto è gestito internamente da SpringBoot.

Nel mio caso, voglio usare Mysql e Mongodb e la soluzione era usare le annotazioni EnableMongoRepositories e EnableJpaRepositories sulla mia class di applicazione.

 @SpringBootApplication @EnableTransactionManagement @EnableMongoRepositories(includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository)) @EnableJpaRepositories(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MongoRepository)) class TestApplication { ... 

NB: Tutte le quadro mysql devono estendere JpaRepository e le JpaRepository mongo devono estendere MongoRepository .

Le configurazioni dell’origine dati sono semplici come presentato dalla documentazione di spring:

 //mysql db config spring.datasource.url= jdbc:mysql://localhost:3306/tangio spring.datasource.username=test spring.datasource.password=test #mongodb config spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=tangio spring.data.mongodb.username=tangio spring.data.mongodb.password=tangio spring.data.mongodb.repositories.enabled=true 

una volta che inizi a lavorare con jpa e un po ‘di driver è nel tuo percorso class, l’avvio a molla lo mette subito dentro come origine dati (es. h2) per usare l’origine dati di defult quindi dovrai solo definire

 spring.datasource.url= jdbc:mysql://localhost:3306/ spring.datasource.username=test spring.datasource.password=test 

se andiamo avanti di un passo e ne vogliamo usare due, consiglierei di usare due fonti di dati come spiegato qui: Spring Boot Configure e Use Two DataSources

Aggiornamento 2018-01-07 con Spring Boot 1.5.8.RELEASE

Se vuoi sapere come configurarlo, come usarlo e come controllare la transazione. Potrei avere delle risposte per te.

Puoi vedere l’esempio eseguibile e alcune spiegazioni in https://www.surasint.com/spring-boot-with-multiple-databases-example/

Ho copiato del codice qui.

Per prima cosa devi impostare application.properties come questa

 #Database database1.datasource.url=jdbc:mysql://localhost/testdb database1.datasource.username=root database1.datasource.password=root database1.datasource.driver-class-name=com.mysql.jdbc.Driver database2.datasource.url=jdbc:mysql://localhost/testdb2 database2.datasource.username=root database2.datasource.password=root database2.datasource.driver-class-name=com.mysql.jdbc.Driver 

Quindi definirli come provider (@Bean) in questo modo:

 @Bean(name = "datasource1") @ConfigurationProperties("database1.datasource") @Primary public DataSource dataSource(){ return DataSourceBuilder.create().build(); } @Bean(name = "datasource2") @ConfigurationProperties("database2.datasource") public DataSource dataSource2(){ return DataSourceBuilder.create().build(); } 

Nota che ho @Bean (name = “datasource1”) e @Bean (name = “datasource2”), quindi puoi usarlo quando abbiamo bisogno di datasource come @Qualifier (“datasource1”) e @Qualifier (“datasource2”), per esempio

 @Qualifier("datasource1") @Autowired private DataSource dataSource; 

Se ti interessa la transazione, devi definire DataSourceTransactionManager per entrambi, come questo:

 @Bean(name="tm1") @Autowired @Primary DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) { DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource); return txm; } @Bean(name="tm2") @Autowired DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) { DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource); return txm; } 

Quindi puoi usarlo come

 @Transactional //this will use the first datasource because it is @primary 

o

 @Transactional("tm2") 

Questo dovrebbe essere sufficiente. Vedi esempio e dettagli nel link sopra.

MySqlBDConfig.java

 @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "mysqlEmFactory" ,transactionManagerRef = "mysqlTransactionManager") public class MySqlBDConfig{ @Autowired private Environment env; @Bean(name="mysqlProperities") @ConfigurationProperties(prefix="spring.mysql") public DataSourceProperties mysqlProperities(){ return new DataSourceProperties(); } @Bean(name="mysqlDataSource") public DataSource interfaceDS(@Qualifier("mysqlProperities")DataSourceProperties dataSourceProperties){ return dataSourceProperties.initializeDataSourceBuilder().build(); } @Primary @Bean(name="mysqlEmFactory") public LocalContainerEntityManagerFactoryBean mysqlEmFactory(@Qualifier("mysqlDataSource")DataSource mysqlDataSource,EntityManagerFactoryBuilder builder){ return builder.dataSource(mysqlDataSource).packages("PACKAGE OF YOUR MODELS").build(); } @Bean(name="mysqlTransactionManager") public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEmFactory")EntityManagerFactory factory){ return new JpaTransactionManager(factory); } } 

H2DBConfig.java

 @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "PACKAGE OF YOUR CRUDS USING MYSQL DATABASE",entityManagerFactoryRef = "dsEmFactory" ,transactionManagerRef = "dsTransactionManager") public class H2DBConfig{ @Autowired private Environment env; @Bean(name="dsProperities") @ConfigurationProperties(prefix="spring.h2") public DataSourceProperties dsProperities(){ return new DataSourceProperties(); } @Bean(name="dsDataSource") public DataSource dsDataSource(@Qualifier("dsProperities")DataSourceProperties dataSourceProperties){ return dataSourceProperties.initializeDataSourceBuilder().build(); } @Bean(name="dsEmFactory") public LocalContainerEntityManagerFactoryBean dsEmFactory(@Qualifier("dsDataSource")DataSource dsDataSource,EntityManagerFactoryBuilder builder){ LocalContainerEntityManagerFactoryBean em = builder.dataSource(dsDataSource).packages("PACKAGE OF YOUR MODELS").build(); HibernateJpaVendorAdapter ven = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(ven); HashMap prop = new HashMap<>(); prop.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect")); prop.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql")); em.setJpaPropertyMap(prop); em.afterPropertiesSet(); return em; } @Bean(name="dsTransactionManager") public PlatformTransactionManager dsTransactionManager(@Qualifier("dsEmFactory")EntityManagerFactory factory){ return new JpaTransactionManager(factory); } } 

application.properties

 #---mysql DATASOURCE--- spring.mysql.driverClassName = com.mysql.jdbc.Driver spring.mysql.url = jdbc:mysql://127.0.0.1:3306/test spring.mysql.username = root spring.mysql.password = root #---------------------- #---H2 DATASOURCE---- spring.h2.driverClassName = org.h2.Driver spring.h2.url = jdbc:h2:file:~/test spring.h2.username = root spring.h2.password = root #--------------------------- #------JPA----- spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect spring.jpa.show-sql=true spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false spring.jpa.hibernate.ddl-auto = update spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true 

Application.java

 @SpringBootApplication public class Application { public static void main(String[] args) { ApplicationContext ac=SpringApplication.run(KeopsSageInvoiceApplication.class, args); UserMysqlDao userRepository = ac.getBean(UserMysqlDao.class) //for exemple save a new user using your repository userRepository.save(new UserMysql()); } }