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:
<? Xmlversion = "1.0" encoding = "utf8"?>
<Beansxmlns = "http://www.springframework.org/schema/beans"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xmlns: aop = "http://www.springframework.org/schema/aop"
Xmlns: tx = "http://www.springframework.org/schema/tx"
Xmlns: context = "http://www.springframework.org/schema/context"
Xsi: schemaLocation ="
Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
Http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
Default-autowire = "byName" default-lazy-init = "false">
<! -- In this example, the DBCP connection pool is used. Copy the jar package of DBCP to the lib directory of the project in advance.
The connection pool configuration is as follows -->
<Beanid = "dataSource" class = "org. apache. commons. dbcp. BasicDataSource">
<Propertyname = "driverClassName" value = "com. mysql. jdbc. Driver"/>
<Propertyname = "url"
Value = "jdbc: mysql: // localhost/courseman"/>
<Propertyname = "username" value = "courseman"/>
<Propertyname = "password" value = "abc123"/>
</Bean>
<Beanid = "sqlSessionFactory" class = "org. mybatis. spring. SqlSessionFactoryBean">
<! -- DataSource attribute specifies the connection pool to be used -->
<Propertyname = "dataSource" ref = "dataSource"/>
<! -- ConfigLocation attribute specifies the core configuration file of mybatis -->
<Propertyname = "configLocation" value = "resources/configuration. xml"/>
</Bean>
<Beanid = "studentMapper" class = "org. mybatis. spring. mapper. MapperFactoryBean">
<! -- SqlSessionFactory attribute specifies the SqlSessionFactory instance to be used -->
<Propertyname = "sqlSessionFactory" ref = "sqlSessionFactory"/>
<! -- MapperInterface attribute specifies the ER interface, which is used to implement this interface and generate the er object -->
<Propertyname = "mapperInterface" value = "com. abc. mapper. StudentMapper"/>
</Bean>
</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.
Package com. demo;
Import org. springframework. context. ApplicationContext;
Import com. abc. mapper. StudentMapper;
Import com. abc. domain. Student;
Import org. springframework. context. support. ClassPathXmlApplicationContext;
Publicclass MyBatisSpringDemo
{
Privatestatic ApplicationContext ctx;
Static
{
// Search for the resources/beans. xml file in the class path
Ctx = new ClassPathXmlApplicationContext ("resources/beans. xml ");
}
Publicstaticvoid main (String [] args)
{
StudentMapper mapper =
(StudentMapper) ctx. getBean ("studentMapper ");
// Only the student with ID 4 is in the author's database. If the reader runs this program,
// Use the student ID in your database. Otherwise, a null pointer exception is reported.
Student student = mapper. getById (4 );
// Use the append operation of StringBuilder to replace the string "+"
// Operations can improve execution efficiency
StringBuilder sb = new StringBuilder ("Student Information: \ n ");
Sb. append ("name :");
Sb. append (student. getName ());
Sb. append ("");
Sb. append ("Major :");
Sb. append (student. getMajor ());
Sb. append ("grade :");
Sb. append (student. getGrade ());
Sb. append ("\ n ");
Sb. append ("instructor information: \ n ");
Sb. append ("name :");
Sb. append (student. getSupervisor (). getName ());
Sb. append ("");
Sb. append ("title :");
Sb. append (student. getSupervisor (). getTitle ());
Sb. append ("");
Sb. append ("research direction :");
Sb. append (student. getSupervisor (). getResearchArea ());
System. out. println (sb. toString ());
}
}
Modify the ant build. xml file and specify this class as the execution class.
<! -- Specify MyBatisSpringDemo as the class to run -->
<Javafork = "true" classname = "com. demo. MyBatisSpringDemo"
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