Spring-boot supports dual data sources Mysql+mongo

Source: Internet
Author: User
Tags mongoclient reflection

Here, the first thing to say is that today's web applications, the processing of data objects, are structured, but also unstructured. exist at the same time. However, when Spring-boot operations the database, if the data source is configured in the properties file, the data source is loaded with the default configuration, it will often only start one.

I'm trying to figure out how to configure the data source, and here's an example of configuring two data sources. MySQL and MONGO, respectively. The persistence of MySQL is based on MyBatis.

MONGO operation is relatively simple, directly affixed to the configuration database code:

 1 package Com.shihuc.dbconn.sourceconfig.mongo; 2 3 Import java.util.Arrays; 4 5 Import Org.springframework.beans.factory.annotation.Value; 6 Import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 7 Import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; 8 Import org.springframework.boot.autoconfigure.mongo.MongoDataAutoConfiguration; 9 Import org.springframework.context.annotation.bean;10 Import ORG.SPRINGFRAMEWORK.CONTEXT.ANNOTATION.COMPONENTSCAN;11 Import ORG.SPRINGFRAMEWORK.CONTEXT.ANNOTATION.CONFIGURATION;12 Import ORG.SPRINGFRAMEWORK.DATA.MONGODB.CONFIG.ABSTRACTMONGOCONFIGURATION;13 Import ORG.SPRINGFRAMEWORK.DATA.MONGODB.REPOSITORY.CONFIG.ENABLEMONGOREPOSITORIES;14 Import com.mongodb.Mongo;16 Import com.mongodb.mongoclient;17 Import com.mongodb.mongocredential;18 import com.mongodb.serveraddress;19 Import Com.mongodb.writeconcern;20 @Configuration22 @EnableAutoConfiguration (Exclude={mongoautoconfiguration.class, MongodataautoconfiguraTion.class}) @ComponentScan24 @EnableMongoRepositories25 public class Mongodatasourceconfig extends Abstractmongoconfiguration{26 @Value ("${mongo.database}")-Private String dbname;29 @Value ("${mongo . Host} ") to private string dbhost;32 @Value (" ${mongo.port} ") private string dbport;35 @Valu E ("${mongo.username}") PNs private string username;38 @Value ("${mongo.password}") + private string Passwo rd;41 @Override43 protected String getdatabasename () {this.dbname;45}46 P Ublic Mongodatasourceconfig () {if (null = = Dbport | | "". Equalsignorecase (Dbport.trim ())) {Dbport = "27017";}51}52 @Override54 @Bean (NA me = "mongods")-Public Mongo Mongo () throws Exception {serveraddress serveradress = new ServerAddress (db        Host, integer.valueof (Dbport)); Mongocredential credential = Mongocredential.createmonGocrcredential (username, dbname, Password.tochararray ());//do not use New Mongo (), is deprecated.59 Mo NGO MONGO = new Mongoclient (serveradress, Arrays.aslist (credential)); Mongo.setwriteconcern (Writeconcern.safe); Mongo;62}63}

MONGO database configuration Inheritance abstractmongoconfiguration, in this process, the spring container will register a mongotemplate, this is very important, later operations MONGO the database, mainly rely on it.

Here the key points are spring-boot and MyBatis integrated operation MySQL configuration and considerations.

 1 package com.shihuc.dbconn.sourceconfig.mysql; 2 3 Import Javax.sql.DataSource; 4 5 Import Org.springframework.beans.factory.annotation.Value; 6 Import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 7 Import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 8 Import Org.springframework.context.annotation.Bean; 9 Import org.springframework.context.annotation.configuration;10 Import Org.springframework.jdbc.datasource.drivermanagerdatasource;11 @Configuration13 @EnableAutoConfiguration (      Exclude = {Datasourceautoconfiguration.class}) public class Mysqldatasourceconfig {@Value ("${mysql.driver}") 17 private string Driver;18 @Value ("${mysql.url}")-private string Url;21 @Value ("${mysql.username}") Username;24 @Value ("${mysql.password}")-private string password;27 @Bean (name= "M Ysqlds ") public DataSource MySQL () {drivermanagerdatasource ds = new DriverManagerdatasource (); Ds.setdriverclassname (driver); Ds.seturl (URL); Ds.setusername (username) ; Ds.setpassword (password); return ds;37}38}

This is the DataSource configuration, note, similar to the MONGO configuration, to the automatic configuration of the class to exclude off. Let spring handle only the data source we want. Otherwise, it will be affected by the information under Classpath, interfering with the configuration of the data source.

In addition, it is the MyBatis configuration. Since Spring-boot is a pure Java config feature, the Java configuration and annotations are also used to enable MyBatis.

1 package com.shihuc.dbconn.sourceconfig.mysql; 2 3 Import Javax.sql.DataSource; 4 5 Import Org.apache.ibatis.session.SqlSessionFactory; 6 Import Org.mybatis.spring.SqlSessionFactoryBean; 7 Import Org.mybatis.spring.annotation.MapperScan; 8 Import org.springframework.beans.factory.annotation.Autowired; 9 Import org.springframework.beans.factory.annotation.qualifier;10 Import ORG.SPRINGFRAMEWORK.CONTEXT.ANNOTATION.BEAN;11 Import org.springframework.context.annotation.configuration;12 13 @ Configuration14 @Mapperscan (basepackages = "Com.shihuc.dbconn.dao.mysql")public class Mysqlmybatisconfig {@Autowired18 @Qualifier ("Mysqlds") private DataSource mysqlds; @Bean22 public Sqlsessionfactory Sqlsessionfactorybean () throws Exception {final SQLSESSIONFA Ctorybean sessionfactory = new Sqlsessionfactorybean (); Sessionfactory.setdatasource (Mysqlds); Sessionfactory.getobject (); 26}27}

Here, Mapperscan primarily sets the root path for configuring mappings between JavaBean and persisted objects. In this example, the mapper part, in fact, is through insert,delete,update,select and other annotations, combined with specific SQL statements to achieve the ORM relationship. Look at the code here:

1 package com.shihuc.dbconn.dao.mysql; 2  3 import org.apache.ibatis.annotations.Insert; 4 import org.apache.ibatis.annotations.Select; 5  6 Import Com.shihuc.dbconn.pojo.mysql.MysqlUser; 7  8 Public interface Imysqluser {9     @Select ("SELECT * from user WHERE id = #{userid}") one public     Mysqluser g  Etuser (int userId);     @Insert ("Insert into user (username, job, age, hometown) values (#{username}, #{job}, #{age}, #{hometown}) ") Public     int AddUser (mysqluser user); 15}

In addition, the definition of the mysqluser used in conjunction with this imysqluser is also very important, mainly the constructor function inside, usually, add data, such as the above AddUser operation, is to create a Pojo object, for convenience, Usually creates a constructor with parameters, note that you must also create a parameterless constructor, otherwise, the following error occurs when you do a query operation, such as the above GetUser:

 1. ____ _ _ _ _ 2/\\/___ _ _ _ _ (_) _ __ _ \ \ \ 3 (() \___ | ' _ | ' _| | ' _ \ _ ' | \ \ \ 4 \\/___) | |_) | | | | | | |  (_| | ))) 5 ' |____|. __|_| |_|_| |_\__, | /////6 =========|_|==============|___/=/_/_/_/7:: Spring Boot:: (v1.2.7.release) 8 9 2016-01-29 15:01:07.9 INFO 30880---[main] com.shihuc.dbconn.DbConnApp:Starting Dbconnapp on Cloudgame with PID 3  0880 (/home/webwps/dbconn/target/classes started by root in/home/webwps/dbconn) 2016-01-29 15:01:07.997 INFO 30880--- [Main] s.c.a.annotationconfigapplicationcontext:refreshing Org.spring[email protected]a85aa40:startup Date [Fri Jan 15:01:07 CST 2016]; Root of context Hierarchy11 2016-01-29 15:01:09.887 INFO 30880---[main] Trationdelegate$beanpostprocessorche Cker:bean ' mysqldatasourceconfig ' of type [class com.shihuc.dbconn.sourceconfig.mysql.mysqldatasourceconfig$$ ENHANCERBYSPRINGCGLIB$$63C6820A]Is isn't eligible for getting processed by all beanpostprocessors (for example:not eligible for auto-proxying) 12 2016-01-29 15:01:09.915 INFO 30880---[main] o.s.j.d.drivermanagerdatasource:loaded JDBC DRIVER:COM.MYSQL.J Dbc. Driver13 2016-01-29 15:01:09.923 INFO 30880---[main] trationdelegate$beanpostprocessorchecker:bean ' mysqld s ' of type [class Org.springframework.jdbc.datasource.DriverManagerDataSource] is isn't eligible for getting processed by al L beanpostprocessors (for example:not eligible for auto-proxying) 2016-01-29 15:01:09.926 INFO 30880---[m Ain] Trationdelegate$beanpostprocessorchecker:bean ' mysqlmybatisconfig ' of type [class com.shihuc.dbconn.sourceconfig.mysql.mysqlmybatisconfig$ $EnhancerBySpringCGLIB $ $bbfde 9e4] is isn't eligible for Getting processed by all beanpostprocessors (for example:not eligible for auto-proxying) 2016-01-29 15:01:09.991 INFO 30880---[main] trationdelegate$beanpostprocessorchecKer:bean ' Sqlsessionfactorybean ' of type [class Org.apache.ibatis.session.defaults.DefaultSqlSessionFactory] is not Eligible for getting processed by all beanpostprocessors (for example:not eligible for auto-proxying) 16 2016-01-29 15:01: 10.040 INFO 30880---[main] trationdelegate$beanpostprocessorchecker:bean ' imysqluser ' of type [class ORG.M Ybatis.spring.mapper.MapperFactoryBean] is not eligible for getting processed by all beanpostprocessors (for Example:not        Eligible for auto-proxying) 2016-01-29 15:01:10.876 INFO 30880---[main] o.s.j.e.a.annotationmbeanexporter : Registering beans for JMX exposure on STARTUP18 2016-01-29 15:01:10.888 INFO 30880---[main] Com.shi Huc.dbconn.DbConnApp:Started Dbconnapp in 3.274 seconds (JVM running for 3.561), Exception in thread "main "Org.mybatis.spring.MyBatisSystemException:nested exception is org.apache.ibatis.reflection.ReflectionException: Error Instantiating class Com.shihuC.dbconn.pojo.mysql.mysqluser with invalid types () or values (). Cause:java.lang.nosuchmethodexception:com.shihuc.dbconn.pojo.mysql.mysqluser.<init> () at Org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible (mybatisexceptiontranslator.java:75) At Org.mybatis.spring.sqlsessiontemplate$sqlsessioninterceptor.invoke (sqlsessiontemplate.java:371) at Com.sun . Proxy. $Proxy 26.selectOne (Unknown Source) at Org.mybatis.spring.SqlSessionTemplate.selectOne ( sqlsessiontemplate.java:163) at Org.apache.ibatis.binding.MapperMethod.execute (mappermethod.java:63) at Org.ap     Ache.ibatis.binding.MapperProxy.invoke (mapperproxy.java:43) at Com.sun.proxy. $Proxy 34.getUser (Unknown Source) 27 At Com.shihuc.dbconn.service.mysql.MysqlUserService.getUser (mysqluserservice.java:20) Com.shihuc.dbconn.DbConnApp.main (dbconnapp.java:34) caused by:org.apache.ibatis.reflection.ReflectionException : Error Instantiating class Com.shihuc.dbconn.poJo.mysql.MysqlUser with invalid types () or values (). Cause:java.lang.nosuchmethodexception:com.shihuc.dbconn.pojo.mysql.mysqluser.<init> () at Org.apache.ibatis.reflection.factory.DefaultObjectFactory.instantiateClass (defaultobjectfactory.java:83) at Org.apache.ibatis.reflection.factory.DefaultObjectFactory.create (defaultobjectfactory.java:45) Org.apache.ibatis.reflection.factory.DefaultObjectFactory.create (defaultobjectfactory.java:38) at Org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createResultObject (Defaultresultsethandler.java : 530) at Org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createResultObject ( defaultresultsethandler.java:509) at Org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue ( defaultresultsethandler.java:329) at Org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap ( defaultresultsethandler.java:289) PNs at Org.apache.ibatis.exEcutor.resultset.DefaultResultSetHandler.handleRowValues (defaultresultsethandler.java:264) at Org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet (defaultresultsethandler.java:234) At Org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets (Defaultresultsethandler.java : £ º + at Org.apache.ibatis.executor.statement.PreparedStatementHandler.query (preparedstatementhandler.java:57) Org.apache.ibatis.executor.statement.RoutingStatementHandler.query at org (routingstatementhandler.java:70) . Apache.ibatis.executor.SimpleExecutor.doQuery (simpleexecutor.java:57) at Org.apache.ibatis.executor.BaseExecutor.queryFromDatabase (baseexecutor.java:259) at Org.apache.ibatis.executor.BaseExecutor.query (baseexecutor.java:132) at Org.apache.ibatis.executor.CachingExecutor.query (cachingexecutor.java:105) at Org.apache.ibatis.executor.CachingExecutor.query (cachingexecutor.java:81) at org.apache.ibatis.sesSion.defaults.DefaultSqlSession.selectList (defaultsqlsession.java:104) at Org.apache.ibatis.session.defaults.DefaultSqlSession.selectList (defaultsqlsession.java:98) at Org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne (defaultsqlsession.java:62) at SUN.REFLECT.NATIVEMETHODACCESSORIMPL.INVOKE0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke ( nativemethodaccessorimpl.java:57) at Sun.reflect.DelegatingMethodAccessorImpl.invoke ( delegatingmethodaccessorimpl.java:43) in Java.lang.reflect.Method.invoke (method.java:606) at Org.mybatis.sprin G.sqlsessiontemplate$sqlsessioninterceptor.invoke (sqlsessiontemplate.java:358) 55 ... 7 more56 caused by:java.lang.nosuchmethodexception:com.shihuc.dbconn.pojo.mysql.mysqluser.<init> () at Java. Lang. Class.getconstructor0 (class.java:2892), at Java.lang.Class.getDeclaredConstructor (class.java:2058), at Org.apach E.ibatis.reflection.factory.defaultobjectfactory.instantiaTeclass (defaultobjectfactory.java:57) 60 ... More61 2016-01-29 15:01:11.139 INFO 30880---[Thread-1] s.c.a.annotationconfigapplicationcontext:closing org . spring[email protected]a85aa40:startup date [Fri Jan 15:01:07 CST 2016];        Root of context hierarchy62 2016-01-29 15:01:11.142 INFO 30880---[Thread-1] o.s.j.e.a.annotationmbeanexporter : Unregistering jmx-exposed beans on shutdown
View Code

Easy to explain the problem, the Mysqluser is also attached to the code:

1 package com.shihuc.dbconn.pojo.mysql;  2  3 import com.shihuc.dbconn.pojo.User; 4  5 public class Mysqluser extends user{6  7     private static final Long serialversionuid = -6412107575129572581l; 8  9     //This ID is the primary key value that is obtained by setting auto_increment in the database, and the     private int id;11 the public     int getId () {The         return ID ;     }15 public     void setId (int id) {         this.id = id;18     }19, public      Mysqluser () /c18>{21     }23     mysqluser (string username, string job, int age , string Hometown){         this.username = username;26         this.job = job;27         this.age = age;28         this.hometown = hometown;29     }30     31}

Let's take a look at the test program, which I wrote in the main function, as follows:

 1 package com.shihuc.dbconn; 2 3 Import org.springframework.boot.SpringApplication; 4 Import org.springframework.boot.autoconfigure.SpringBootApplication; 5 Import Org.springframework.context.ApplicationContext; 6 Import Org.springframework.context.annotation.PropertySource; 7 8 Import Com.shihuc.dbconn.pojo.mongo.MongoUser; 9 Import com.shihuc.dbconn.pojo.mysql.mysqluser;10 Import com.shihuc.dbconn.service.mongo.mongouserservice;11  Import com.shihuc.dbconn.service.mysql.mysqluserservice;12/**14 * @author SHIHUC16 * @date Jan 29, 201617        * */19 @SpringBootApplication20 @PropertySource (value = "Dbconn.properties") public class Dbconnapp 22 {23 24 public static void Main (string[] args) throws Throwable {springapplication app = new Springa        Pplication (Dbconnapp.class); ApplicationContext ctx = App.run (args); Mysqluserservice Mysqluserservice = (mysqluserservice) ctx.getbean ("MysqluseRservice ");    //Mysqluser su = new Mysqluser ("Shihuc", "SW", +, "Wuhan"); +//Mysqluserservice.adduser (SU);        Mysqluser UE = Mysqluserservice.getuser (1), System.out.println ("Mysql User:" + UE); Mongouserservice Mongouserservice = (mongouserservice) ctx.getbean ("Mongouserservice"); PNS//M                Ongouser mu = new Mongouser ("Shihuc", "SW", "a", "Wuhan");//Mongouserservice.adduser (MU);  Mongouser um = Mongouserservice.getuser ("Shihuc"); + System.out.println ("Mongo User:" + um); 41}42 }

Finally, attach the pom file for my maven project:

 1 <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" 2 xsi : schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > 3 < Modelversion>4.0.0</modelversion> 4 5 <groupId>com.shihuc</groupId> 6 <artifactid>dbconn </artifactId> 7 <version>0.0.1-SNAPSHOT</version> 8 <packaging>jar</packaging> 9 &L T;name>dbconn</name>11 <url>http://maven.apache.org</url>12 <parent>14 <group Id>org.springframework.boot</groupid>15 <artifactid>spring-boot-starter-parent</artifactid >16 <version>1.2.7.release</version>17 </parent>18 <properties>20 <proj Ect.build.sourceencoding>utf-8</project.build.sourceencoding>21 </properties>22 < Dependencies>24 <dependency>25 <groupiD>org.springframework.boot</groupid>26 <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>28 <dependency>29 <groupid>mysql</groupid>30 <artifa ctid>mysql-connector-java</artifactid>31 </dependency>32 <dependency>33 <group Id>org.mybatis</groupid>34 <artifactid>mybatis</artifactid>35 <version>3.2.3&lt         ;/version>36 </dependency>37 <dependency>38 <groupid>org.mybatis</groupid>39 <artifactid>mybatis-spring</artifactid>40 <version>1.2.2</version>41 </depend ency>42 <dependency>43 <groupid>org.springframework.boot</groupid>44 <artifact id>spring-boot-starter-data-mongodb</artifactid>45 </dependency>46 </dependencies>47 &lt ; build>49 <pluGins>50 <plugin>51 <groupid>org.springframework.boot</groupid>52 < artifactid>spring-boot-maven-plugin</artifactid>53 </plugin>54 </plugins>55 </build& gt;56 </project>

It is relatively simple to configure and operate. For this demo example program, you can download it on GitHub https://github.com/shihuc/dbconn.

Http://www.cnblogs.com/shihuc/p/5169418.html

Spring-boot supports dual data sources Mysql+mongo

Related Article

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.