Example of integration of MyBatis and Spring -- MyBatis study Note 5

Source: Internet
Author: User

In this example, the project of the previous blog is rewritten by integrating MyBatis with Spring. To this end, copy the jar packages used by the project to the lib directory of the project. Readers can download the project in this example at the "attachment Download" section below this article. Therefore, the jar package to be used is not described here due to the maximum size limit of a single attachment, you cannot package a project as a file. The first attachment is a project, and the last two attachments are jar packages that cannot be packaged together. After downloading and decompressing the jar packages in the last two attachments, copy them to the lib directory of the Project ).

1. Adhesive required for Integration

Is the mybatis-spring package. This is the jar package officially provided by MyBatis for integration with Spring, which is the core part of the integration, this example uses mybatis-spring-1.1.1.jar.

Ii. Spring Configuration

In this example, Spring 3.1.2 is used.

The configuration file beans. xml is as follows:

 
 
  1. <? Xmlversion = "1.0" encoding = "utf8"?>

  2. <Beansxmlns = "http://www.springframework.org/schema/beans"

  3. Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"

  4. Xmlns: aop = "http://www.springframework.org/schema/aop"

  5. Xmlns: tx = "http://www.springframework.org/schema/tx"

  6. Xmlns: context = "http://www.springframework.org/schema/context"

  7. Xsi: schemaLocation ="

  8. Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

  9. Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

  10. Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

  11. Http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd

  12. Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

  13. Default-autowire = "byName" default-lazy-init = "false">

  14. <! -- In this example, the DBCP connection pool is used. Copy the jar package of DBCP to the lib directory of the project in advance.

  15. The connection pool configuration is as follows -->

  16. <Beanid = "dataSource" class = "org. apache. commons. dbcp. BasicDataSource">

  17. <Propertyname = "driverClassName" value = "com. mysql. jdbc. Driver"/>

  18. <Propertyname = "url"

  19. Value = "jdbc: mysql: // localhost/courseman"/>

  20. <Propertyname = "username" value = "courseman"/>

  21. <Propertyname = "password" value = "abc123"/>

  22. </Bean>

  23. <Beanid = "sqlSessionFactory" class = "org. mybatis. spring. SqlSessionFactoryBean">

  24. <! -- DataSource attribute specifies the connection pool to be used -->

  25. <Propertyname = "dataSource" ref = "dataSource"/>

  26. <! -- ConfigLocation attribute specifies the core configuration file of mybatis -->

  27. <Propertyname = "configLocation" value = "resources/configuration. xml"/>

  28. </Bean>

  29. <Beanid = "studentMapper" class = "org. mybatis. spring. mapper. MapperFactoryBean">

  30. <! -- SqlSessionFactory attribute specifies the SqlSessionFactory instance to be used -->

  31. <Propertyname = "sqlSessionFactory" ref = "sqlSessionFactory"/>

  32. <! -- MapperInterface attribute specifies the ER interface, which is used to implement this interface and generate the er object -->

  33. <Propertyname = "mapperInterface" value = "com. abc. mapper. StudentMapper"/>

  34. </Bean>

  35. </Beans>

Note that the above sqlSessionFactory configuration has its own special features. Its class is org. mybatis. spring. SqlSessionFactoryBean, which implements an interface org. springframework. beans. factory. FactoryBean in Srping. This interface declares a method getObject (). This means that when we want to reference the bean sqlSessionFactory, the returned value is not the instance of SqlSessionFactoryBean, but the return value of the getObject () method of this instance. SqlSessionFactoryBean returns a SqlSessionFactory object to implement this method. That is to say, the instance of SqlSessionFactoryBean is used to generate the SqlSessionFactory object.

The configuration of studentMapper follows the same principle.

Put this file together with the configuration file of MyBatis, that is, under the src \ resources Directory of the project. This directory will be copied to the classes directory by ant, And the classes directory will be added to the class loading path by ant.

3. Configure MyBatis

The data source has been configured in Spring, so the environments element in the configuration. xml file of MyBatis is no longer needed. Other elements are the same as before. The stuing file StudentMapper. xml does not need to be modified.

Iv. Execution

The execution class MyBatisSpringDemo. java) code is as follows.

 
 
  1. Package com. demo;

  2. Import org. springframework. context. ApplicationContext;

  3. Import com. abc. mapper. StudentMapper;

  4. Import com. abc. domain. Student;

  5. Import org. springframework. context. support. ClassPathXmlApplicationContext;

  6. Publicclass MyBatisSpringDemo

  7. {

  8. Privatestatic ApplicationContext ctx;

  9. Static

  10. {

  11. // Search for the resources/beans. xml file in the class path

  12. Ctx = new ClassPathXmlApplicationContext ("resources/beans. xml ");

  13. }

  14. Publicstaticvoid main (String [] args)

  15. {

  16. StudentMapper mapper =

  17. (StudentMapper) ctx. getBean ("studentMapper ");

  18. // Only the student with ID 4 is in the author's database. If the reader runs this program,

  19. // Use the student ID in your database. Otherwise, a null pointer exception is reported.

  20. Student student = mapper. getById (4 );

  21. // Use the append operation of StringBuilder to replace the string "+"

  22. // Operations can improve execution efficiency

  23. StringBuilder sb = new StringBuilder ("Student Information: \ n ");

  24. Sb. append ("name :");

  25. Sb. append (student. getName ());

  26. Sb. append ("");

  27. Sb. append ("Major :");

  28. Sb. append (student. getMajor ());

  29. Sb. append ("grade :");

  30. Sb. append (student. getGrade ());

  31. Sb. append ("\ n ");

  32. Sb. append ("instructor information: \ n ");

  33. Sb. append ("name :");

  34. Sb. append (student. getSupervisor (). getName ());

  35. Sb. append ("");

  36. Sb. append ("title :");

  37. Sb. append (student. getSupervisor (). getTitle ());

  38. Sb. append ("");

  39. Sb. append ("research direction :");

  40. Sb. append (student. getSupervisor (). getResearchArea ());

  41. System. out. println (sb. toString ());

  42. }

  43. }

Modify the ant build. xml file and specify this class as the execution class.

 
 
  1. <! -- Specify MyBatisSpringDemo as the class to run -->

  2. <Javafork = "true" classname = "com. demo. MyBatisSpringDemo"

  3. Classpathref = "library">

The execution result is as follows:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1223303G1-0.png "border =" 0 "/>

5. Possible Errors

1. The jar package version does not match

The MyBatis package I used was a mybatis-3.0.6.jar, But it reported NoSuchMethodError, that is, the setDatabaseId method of org. apache. ibatis. session. configuration could not be found. As shown in:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/1223303636-1.png "border =" 0 "/>

It can be seen that the mybatis-spring component calls this method, and this method mybatis-3.0.6.jar is not provided, so an error is reported. For the mybatis-3.1.1.jar.

2. Character Set Problems

If the encoding of the configuration file in the project is the encoding attribute) is a UTF-8, and then add a Chinese comment to these files, an error similar to "Invalid byte 1 of 1-byte UTF-8 sequence" is reported. As shown in:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/122330MO-2.png "border =" 0 "/>

You can solve this problem by changing the encoding to utf8 or gbk.

MyBatis Study Notes series I: download and install ant

Prepare for MyBatis Study Notes Series II: ant getting started

MyBatis learning notes: MyBatis getting started

MyBatis Study Notes Series II: Example of adding, deleting, and modifying MyBatis

MyBatis Study Notes Series 3: association examples of MyBatis

MyBatis Study Notes Series 4: two forms of MyBatis association

MyBatis Study Notes Series 5: examples of integration between MyBatis and Spring

MyBatis Study Notes Series 6: examples of integration between MyBatis and Spring

MyBatis study notes 7: MyBatis one-to-multiple bidirectional Association

MyBatis Study Notes: MyBatis MapperScannerConfigurer Configuration

MyBatis Study Notes: two forms of MyBatis collection

MyBatis Study Notes Series 10: Log4j example of MyBatis logs

MyBatis Study Notes: example of how to annotate MyBatis with multiple parameters

MyBatis learning notes: Example of the default naming method for MyBatis multi-parameter transfer

MyBatis Study Notes: Example of Map mode for MyBatis multi-parameter transfer

MyBatis Study Notes: N + 1 in MyBatis

MyBatis Study Notes: a hybrid transfer of multiple parameters in MyBatis

MyBatis learning notes: Example of Spring declarative Transaction Management

MyBatis Study Notes: Example of MyBatis multiple-to-multiple storage

This article is from the "Xiao fan's column" blog, please be sure to keep this source http://legend2011.blog.51cto.com/3018495/946579

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.