Springmvc camel mybatis integrated instance and Analysis

Source: Internet
Author: User
Tags cdata
Recently, I have been studying camel and used camel in my previous projects. Even database operations are performed through camel. As for the advantages of using camel to operate databases, I have my own experience. Using camel can simplify the CRUD operation on the service layer. Code . Before camel was useless, I had a corresponding service to process crud operations on various objects. Even if many of these services simply inherit a crudservcie and then use generics to restrict the Entity objects processed by the Service. In this way, there are many service interfaces and implementation classes, but the repetition rate is extremely high. If camel is used, you can use camel to write a common service. No matter what kind of entity class operation you are using, you only need to input the type and method name to be called. Because it involves company secrets, I will not post mature Source code But I can provide a column of my own. I think the above results can be achieved through a slight improvement from this column. The architecture of the example is as follows: springmvc camel mybatis is managed by Maven, and its Pom. XML content can be viewed by downloading the sub-source code of the column. Springmvc configurations do not need to be pasted out and can be seen everywhere. Here we will focus on some configuration items in the spring and configuration files, especially the following section:
<! -- Use transaction control for data source configuration --> <bean id = "mydatasource" class = "org. apache. commons. DBCP. basicdatasource "Destroy-method =" close "> <property name =" driverclassname "value =" com. mySQL. JDBC. driver "/> <property name =" url "value =" JDBC: mysql: // localhost: 3306/test? Characterencoding = UTF-8 "/> <property name =" username "value =" root "/> <property name =" password "value =" fanly "/> <property name =" defaultautocommit "value =" false "/> </bean> <bean id =" transactionmanager "class =" org. springframework. JDBC. datasource. datasourcetransactionmanager "> <property name =" datasource "ref =" mydatasource "/> </bean> <bean id =" sqlsessionfactory "class =" org. mybatis. spring. sqlsessionfacto Rybean "> <property name =" datasource "ref =" mydatasource "/> <property name =" configlocation "value =" classpath: sqlmapconfig. XML "/> </bean> <bean id =" required "class =" org. apache. camel. spring. SPI. springtransactionpolicy "> <property name =" transactionmanager "ref =" transactionmanager "/> <property name =" propagationbehaviorname "value =" propagation_required "/> </bean> <bean id =" mybatis "class =" org. apache. Camel. component. mybatis. mybatiscomponent "> <property name =" sqlsessionfactory "ref =" sqlsessionfactory "/> </bean> <! -- End of data source configuration -->
Note that the configuration of the last item, through the mybatiscomponent class, camel will know how to interact with mybatis through the route set by the user. This mybatiscomponent implements the Component Interface of camel. For what the component interface is for, refer to my blog or go to the official manual. In fact, you can understand component as the standard for communication between camelcontext and other systems. Different systems implement the component interface, and you can use this interface to communicate with camel standard APIs. Note that mybatiscomponent has a configurationuri attribute, whose default value is sqlmapconfig. XML, that is, mybatiscomponent loads sqlmapconfig under the class path by default. XML initializes some configuration and user-written er files. Of course, you can modify this default behavior. How can this be modified? Inject your configuration file location through property. It should be pointed out that when we used mybatis separately, one way is to define a er ER interface and then in the corresponding mapper. set the namespace of the er price in XML to the full path of the Mapper interface. In this way, mybatis will use mapper during runtime. the proxy class generated by XML is used as the implementation class of the Mapper interface. Program Provides services at the data access layer. So when we use mybatiscomponent to interact with the database, do we need to define the ER interface? It turns out that we no longer need to define the ER interface. We only need to implement Mapper. xml. How does mybatiscomponent load the er. xml implemented by us? You only need to specify our Mapper. xml file in sqlmapconfig. xml. The content of the sqlmapconfig. xml file in this example code is as follows:
<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype configuration public "-// mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <Settings> <setting name = "cacheenabled" value = "true"/> </ settings> <mappers> <mapper resource = "com/ugarden/mapper/usermapper. XML "/> </mappers> </configuration>
Let's take a look at the content of usermapper. xml:
<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype mapper public "-// mybatis.org//dtd mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. ugarden. repository. usermapper "> <resultmap id =" userresult "type =" com. ugarden. entity. user "> <result property =" ID "column =" ID "/> <result property =" email "column =" email "/> <result property =" realname "column = "real_name"/> <result property = "password" column = "password"/> </result Map> <SQL id = "columns"> <! [CDATA [ID, password, email, show_name, real_name]> </SQL> <insert id = "batchinsertusers" parametertype = "list" usegeneratedkeys = "false"> <! [CDATA [insert into kf_user (ID, password, email, real_name) values]> <foreach collection = "list" item = "item" separator = ","> <! [CDATA [(# {item. id}, # {item. password}, # {item. email },# {item. realname})]> </foreach> </Insert> <insert id = "insert" parametertype = "com. ugarden. entity. user "usegeneratedkeys =" false "keyproperty =" ID "> <! [CDATA [insert into kf_user (ID, password, email, real_name) values (# {ID}, # {password}, # {email}, # {realname})]> </Insert> <update id = "Update" parametertype = "com. ugarden. entity. user "> <! [CDATA [update kf_user set password =#{ password}, email =#{ email}, real_name =#{ realname }, where id = # {ID}]> </update> <Delete id = "deleteusersrolesbyid" parametertype = "string"> <! [CDATA [Delete from kf_user_role where user_id =#{ userid}]> </delete> </mapper>
We have also set namespace = "com. ugarden. repository. usermapper ", but there is no corresponding interface in my project. It is not set here to see if there is any problem. I haven't tried it before writing this article. Writing is always better to avoid confusion. How can we operate databases through the camel API? The content of userservcie. Java is as follows:
 
@ Servicepublic class userservice {@ autowiredprivate producertemplate; @ autowiredprivate camelcontext; Public void insertuser () throws exception {// init test user entityuser user = new user (); User. setemail ("fanly" + system. currenttimemillis () + "@ 126.com"); User. setpassword ("123456"); User. setid (string. valueof (system. currenttimemillis (); User. setrealname ("double"); Exchange in = This. camelcontext. getendpoint ("Direct: Start "). createexchange (exchangepattern. inout); In. getin (). setbody (User); exchange out = This. producertemplate. send ("mybatis: insert? Statementtype = Insert ", in); If (null! = Out. getexception () {Throw out. getexception ();}}}
After learning about camel, the children's shoes will immediately understand that, first obtain an endpoint through camelcontext and then the exchange object in the input process. Because the data source is provided by our program, therefore, the endpoint URI is set to direct: Start. Then add the user object we want to add to the body of the message object, and then route our message object to the database. We send a message to the camelcontext object through the producertemplate object, the route information is attached to the first parameter, that is, "mybatis: insert? Statementtype = Insert "if you do not understand the meaning of this parameter, go to the camel official website to see the description of camel-mybatis. This statement tells the camelcontext object that I want to call an insert method through the component object mybatis. The statement type of this method is insert, insert the data in the body of the message object to the database. You may ask, where does the producertemplate and camelcontext in your service come from? Why do you use "mybatis: insert? Statementtype = Insert "parameter. Does camelcontext know which component to find for routing? Do not panic. Please refer to the following configuration content in the spring root configuration file:
 
<! -- Camel context Inti --> <camelcontext id = "Camel" trace = "true" xmlns = "http://camel.apache.org/schema/spring"> <package> com. ugarden </package> </camelcontext>
Camelcontext exists when spring is started. If you have multiple camelcontext instances, you need to use IDs to differentiate injection. Where did the producertemplate come from? At the beginning, I also struggled with this problem. Finally, I checked the method annotation of the createproducertemplate of camelcontext and found that it was initialized with camelcontext, which can explain why spring can help us inject data. How does camel know "mybatis: insert? In statementtype = Insert ", what does mybatis mean? Do you still remember this configuration?
 
<Bean id = "mybatis" class = "org. apache. camel. component. mybatis. mybatiscomponent "> <property name =" sqlsessionfactory "ref =" sqlsessionfactory "/> </bean>
Let's look at his ID. I think if there are multiple data sources, I will make the following Configuration:
 
<Bean id = "mybatis1" class = "org. apache. camel. component. mybatis. mybatiscomponent "> <property name =" sqlsessionfactory "ref =" sqlsessionfactory "/> </bean>
Can I use "mybatis1: insert? Statementtype = Insert "what about routing? I will try it after I have tried it. The official URI support scope of camel definitely does not include mybatis1. Now return Article In the beginning, how do we use camel to create a uniform service layer? It is very simple. We only need the method name to be called, and the object to be routed to the database in the body can accommodate all changes if it is passed in through parameters? From then on, we only need to generate the following Mapper. xml through the data table. Thanks for the special SQL. As long as it is a database operation, we can use a superservice class implemented by camel. Finally, the source code of the example is provided for children's shoes to download and exchange. The project is free of points in my resource section.

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.