6. Configure multiple data sources in spring boot 1.5.4, spring1.5.4

Source: Internet
Author: User
Tags findone

6. Configure multiple data sources in spring boot 1.5.4, spring1.5.4

Spring boot supports multi-data source configuration and does not need to write many classes on the Internet. This is especially troublesome. Please take a look at the following solutions officially. Rest assured!

 

1. First define the data source configuration

#=====================multiple database config============================
#ds1
first.datasource.url=jdbc:mysql://localhost/test?characterEncoding=utf8&useSSL=true
first.datasource.username=root
first.datasource.password=123456
first.datasource.driver-class-name=com.mysql.jdbc.Driver
first.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
first.datasource.max-wait=10000
first.datasource.max-active=200
first.datasource.test-on-borrow=true
first.datasource.initial-size=10

#ds2
second.datasource.url=jdbc:mysql://localhost/test2?characterEncoding=utf8&useSSL=true
second.datasource.username=root
second.datasource.password=123456
second.datasource.driver-class-name=com.mysql.jdbc.Driver
second.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
second.datasource.max-wait=10000
second.datasource.max-active=200
second.datasource.test-on-borrow=true
second.datasource.initial-size=10

#================================== Jpa config ====================== ======================
# Specific actions of the entity class to maintain the database table structure: update/create-drop/validate/none
Spring. jpa. hibernate. ddl-auto = none
# Print SQL statements
Spring. jpa. show-SQL = true
# Format the output json string
Spring. jackson. serialization. indent_output = true


2. Configure related injection objects of ds1 and enable jpa support
/*** Created by hdwang on 2017-06-16. * configure the first Data source * If you are using Spring Data, you need to configure @ EnableJpaRepositories */@ Configuration @ EnableTransactionManagement @ EnableJpaRepositories (basePackages = "com. hdwang. dao. datajpa. firstDs ", entityManagerFactoryRef =" firstEntityManagerFactory ", transactionManagerRef =" firstTransactionManager ") public class FirstDsConfig {/*** data source configuration object * Primary indicates the default object and Autowire can be injected, otherwise, you must specify the name * @ return */@ Bean @ Primary @ ConfigurationProperties ("first. datasource ") public performanceproperties firstperformanceproperties () {return new performanceproperties ();}/*** data source object ** @ return */@ Bean @ Primary @ ConfigurationProperties (" first. datasource ") public DataSource firstDataSource () {return firstDataSourceProperties (). initializeDataSourceBuilder (). build ();}/*** object management object ** @ param builder inject this object by spring. First, inject the object according to type (multiple objects will be declared @ Primary ), otherwise, inject * @ return */@ Bean @ Primary public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory (EntityManagerFactoryBuilder builder) {return builder. dataSource (firstDataSource ()). packages ("com. hdwang. entity. dbFirst "). persistenceUnit ("firstDs "). build ();}/*** transaction management object * @ return */@ Bean (name = "firstTransactionManager") @ Primary public PlatformTransactionManager transactionManager (EntityManagerFactory emf) {JpaTransactionManager transactionManager = new JpaTransactionManager (); transactionManager. transform (emf); return transactionManager;} @ Bean @ Primary public JdbcTemplate jdbcTemplate () {return new JdbcTemplate (firstDataSource ();} @ Bean @ Primary public TransactionTemplate transactionTemplate (PlatformTransactionManager platformTransactionManager) {return new TransactionTemplate (platformTransactionManager );}}

 

Related Knowledge points:
1. You can use @ Bean to create a bean object and hand it over to spring container management.
2. @ The Name Of The Bean object created by bean is the method name by default. You can also specify
3. @ Bean method parameter indicates that a bean object is received. By default, the injected object is received according to the type. to change it to the byName method, you can use the @ Qualifier annotation to inject accurate objects.
4. @ Primary indicates that the bean is the default bean of this type. When referenced elsewhere, @ Autowired can be used to inject the bean by type, which is not affected by multiple objects of the same type.
5. EnableJpaRepositories indicates to enable spring data jpa support, that is, the new usage of jpa. Note that basePackages indicates the position of the package where the @ Repository interface is located. You can configure multiple
Other annotations are unclear!

2. Configure related injection objects of ds2 and enable jpa support
@ Configuration @ EnableTransactionManagement @ EnableJpaRepositories (basePackages = "com. hdwang. dao. datajpa. secondDs ", entityManagerFactoryRef =" secondEntityManagerFactory ", transactionManagerRef =" secondTransactionManager ") public class SecondDsConfig {@ Bean @ ConfigurationProperties (" second. datasource ") public performanceproperties secondperformanceproperties () {return new performanceproperties () ;}@ Bean @ ConfigurationProperties (" second. datasource ") public DataSource secondDataSource () {return secondperformanceproperties (). initializeDataSourceBuilder (). build ();}/*** object management object ** @ param builder inject this object by spring. First, inject the object according to type (multiple objects will be declared @ Primary ), otherwise, inject * @ return */@ Bean public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory (EntityManagerFactoryBuilder builder) {return builder according to the name. dataSource (secondDataSource ()). packages ("com. hdwang. entity. dbSecond "). persistenceUnit ("secondDs "). build ();}/*** transaction management object ** @ param secondEntityManagerFactory Object Management factory object (injection by name) * @ return platform Transaction Manager */@ Bean (name = "secondTransactionManager") public PlatformTransactionManager transactionManager (@ Qualifier ("Courier") implements secondEntityManagerFactory) {JpaTransactionManager transactionManager = new JpaTransactionManager (); transactionManager. setEntityManagerFactory (secondEntityManagerFactory. getObject (); return transactionManager;} @ Bean (name = "jdbcTemplate2") public JdbcTemplate jdbcTemplate () {return new JdbcTemplate (secondDataSource ());} @ Bean (name = "transactionTemplate2") public TransactionTemplate transactionTemplate (@ Qualifier ("secondTransactionManager") PlatformTransactionManager transactionManager) {return new TransactionTemplate (transactionManager );}}

 

 

3. Repository data persistence layer

Package com. hdwang. dao. datajpa. firstDs; @ Repositorypublic interface UserRepository extends JpaRepository <User, Integer> {/*** spring data jpa will be automatically injected for implementation (according to method naming Rules) * @ return */User findByNumber (String number); @ Modifying @ Query ("delete from User u where u. id =: id ") void deleteUser (@ Param (" id ") int id );}
Package com. hdwang. dao. datajpa. secondDs; @ Repositorypublic interface OrderRepository extends JpaRepository <Order, Integer> {/*** spring data jpa will be automatically injected for implementation (according to method naming Rules) * @ return */User findByNumber (String number); @ Modifying @ Query ("delete from Order o where o. id =: id ") void deleteUser (@ Param (" id ") int id );}

 

The preceding two interfaces belong to two data sources. After @ EnableJpaRepositories is configured, you can operate the corresponding data source correctly.


4. Service layer, pay attention to things (I will not post interfaces)
@Service@Transactional("firstTransactionManager")public class UserServiceImpl implements UserService {    @Autowired    private UserRepository userRepository;    @Override    public User findById(int id) {        return this.userRepository.findOne(id);    }    @Override    public User findByNumber(String number) {        return this.userRepository.findByNumber(number);    }    @Override    public List<User> findAllUserByPage(int page,int size) {        Pageable pageable = new PageRequest(page, size);        Page<User> users =  this.userRepository.findAll(pageable);        return users.getContent();    }    @Override    public User updateUser(User user,boolean throwEx) {        User userNew = this.userRepository.save(user);        if(throwEx){            throw new RuntimeException("throw a ex");        }        return userNew;    }    @Override    public void deleteUser(int id) {        this.userRepository.deleteUser(id);    }}
@Service@Transactional("secondTransactionManager")public class OrderServiceImpl implements OrderService {    @Autowired    private OrderRepository orderRepository;    @Override    public Order findById(int id) {        return this.orderRepository.findOne(id);    }    @Override    public Order updateOrder(Order order, boolean throwEx) {        Order orderNew = this.orderRepository.save(order);        if(throwEx){            throw new RuntimeException("throw a ex");        }        return orderNew;    }}

 



Knowledge Extension

1. If the traditional jpa method is used, @ EnableJpaRepositories does not need to be configured, And the configuration is not affected. The implementation method is as follows:

Ds1 related DaoImpl
@ PersistenceContext
Private EntityManager entityManager;

Ds2 related DaoImpl
@ PersistenceContext (unitName = "secondDs ")
Private EntityManager entityManager;

Because the entityManger of ds1 declares @ Primary, you do not need to specify unitName. ds2 must specify. If you inject an accurate entityManager, you can directly operate the database. The service layer is the same as the above. @ Transactional ("xxxManager") indicates the Transaction Manager!


2. Use the jdbcTemplate method to directly inject the object to the Service layer. so easy!
@ Autowired
Private JdbcTemplate jdbcTemplate;

@ Autowired
Private TransactionTemplate transactionTemplate;

@ Resource (name = "jdbcTemplate2 ")
Private JdbcTemplate jdbcTemplate2;

@ Resource (name = "transactionTemplate2 ")
Private TransactionTemplate transactionTemplate2;


All right, spring boot has multiple data sources, perfect solution! All three database operation methods are supported, including transactions. It has been proved by practice! This is the best practice officially provided, but the official documentation is not detailed. It took me a few days. So far, the use of the spring boot framework has come to an end!
 




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.