Explain the integration process of MyBatis and Spring through examples.
preface
This example of MyBatis and Spring integration was written by me when I was transferred to my new post in March this year. I wanted to know how to use MyBatis in Spring from 0 to 1. This example is a reference to “Chinese language of C language”, but the example in it cannot run directly, maybe because of version and other reasons. At that time, it took several days to integrate MyBatis and Spring. Now looking back, if you do not know the basic knowledge of MyBatis, you can solve the problem by directly following the example. But troubleshooting is a pain in the ass, so I’ll give you a complete example of how to integrate the two so you don’t get sidetrack.
Project preparation
Mysql > select * from DB; Mysql > select * from DB;
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.46.</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0. 0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.06.</version>
</dependency>
Copy the code
The DB structure:
CREATE TABLE `user_test` (
`uid` tinyint(2) NOT NULL,
`uname` varchar(20) DEFAULT NULL,
`usex` varchar(10) DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Copy the code
DB initial data:
uid | uname | usex |
---|---|---|
1 | Zhang SAN | female |
2 | Chen Heng | male |
3 | Floor wang | male |
Integration of the sample
Step 1: Create the persistent class
@Data
public class MyUser {
private Integer uid; / / the primary key
private String uname;
private String usex;
}
Copy the code
Step 2: Create the mapping file
<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE mapper PUBLIC"- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.dao.UserDao"> <! Select * from user where id= 0"selectUserById" parameterType="Integer" resultType="com.mybatis.entity.MyUser"> select * from user_test where uid = #{uid} </select> <! --> <select id="selectAllUser" resultType="com.mybatis.entity.MyUser"> select * from user_test </select> <! #{uname} = com.mybatis. Po. MyUser --> <insert id="addUser" parameterType="com.mybatis.entity.MyUser">
insert into user_test (uid,uname,usex)
values(#{uid},#{uname},#{usex})</insert> <! -- Update a user --> <update id="updateUser" parameterType="com.mybatis.entity.MyUser"> update user_test set uname =#{uname},usex = #{usex} where uid = #{uid} </update> <! -- delete a user --> <delete id="deleteUser" parameterType="Integer">
delete from user_test where uid= #{uid}
</delete>
</mapper>
Copy the code
Step 3: Create the interface for the mapping file
@Repository("userDao")
@Mapper
/* * Use Spring to automatically scan and assemble MyBatis interfaces (Spring will automatically assemble all interfaces annotated by @mapper annotations in the specified package as MyBatis mapping interfaces */
public interface UserDao {
/** * id */ in the SQL mapping file corresponding to the interface method
public MyUser selectUserById(Integer uid);
public List<MyUser> selectAllUser(a);
public int addUser(MyUser user);
public int updateUser(MyUser user);
public int deleteUser(Integer uid);
}
Copy the code
Before using MyBatis directly, there is no such interface file. This file is added to enable the operation of Spring and MyBatis to be associated with this file, that is, the operation of DB can be realized through the interface provided above.
Step 4: Create a MyBatis configuration
<? 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="logImpl" value="LOG4J" />
<setting name="cacheEnabled" value="false"/>
<setting name="defaultExecutorType" value="REUSE"/>
<setting name="useGeneratedKeys" value="true"/>
</settings>
</configuration>
Copy the code
Since the two will be integrated later, the configuration of environments and mappers in MyBatis will all be moved to ApplicationContext.xml. This is a big difference in using MyBatis directly.
Step 5: Add a DB profile
Added DB configuration file jdbc.properties to save DB configuration information:
jdbc.shop.url=jdbc:mysql://xxx:3104/xm_jointly? characterEncoding=utf8 jdbc.shop.username=jointly_xx jdbc.shop.password=G-uTlU-xxxCopy the code
Step 6: Add configuration information
You need to add configuration information in applicationContext.xml, and here is the key to the entire integration:
<! For loading configuration files --> <beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"> <value>classpath:com/mybatis/config/datasources/jdbc.properties</value> </property> </bean> <! Define data source --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.shop.url}"></property>
<property name="username" value="${jdbc.shop.username}"></property>
<property name="password" value="${jdbc.shop.password}"></property> </bean> <! Add transaction support --> <bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/> </bean> <! <tx:annotation-driven Transaction-manager ="txManager"/ > <! SqlSessionFactoryBean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <! -- Reference data source component --> <property name="dataSource" ref="dataSource"/ > <! -- reference DB XML configuration file --> <property name="mapperLocations" value="classpath*:com/mybatis/mapper/UserMapper.xml"/ > <! -- Reference the configuration in MyBatis configuration file --> <property name="configLocation" value="classpath:com/mybatis/config/datasources/mybatis-config.xml"/> </bean> <! - Mapper agent development, using Spring to automatically scan the interface of MyBatis and assemble (Spring will specify all packages in the@MapperAnnotated interfaces are automatically assembled into MyBatis mapping interfaces) --> <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"> <! -- The scanner of mybatis- Spring component, com.dao only needs the interface (the interface method is the same as in the SQL mapping file) --> <property name="basePackage" value="com.mybatis.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
Copy the code
This configuration needs to be read:
- Used to load configuration files: Used to store DB configuration information, such as the jdbc.properties configuration file mentioned above, which has the advantage that DB configuration information does not need to be written to XML.
- Jdbc.shop. url and jdbc.shop.username are the DB configuration information stored in the jdbc.properties configuration file.
- Added transaction support: The previously configured transaction support is in MyBatis, environments are now being changed to JDBC. Note that adding a transaction requires registering the transaction management driver.
- Configuration SqlSessionFactoryBean: MyBatis dataSource is the dataSource, mapperLocations is the XML mapping file, and configLocation is the original configuration. Environments and Mappers from inside have been moved here. MyBatis = sqlSessionFactory = sqlSessionFactory
MyBatis is not integrated, so you can know its original appearance, including the following inheritance of Spring Boost, the principle is the same. It’s just a different presentation.
- Spring automatically scans the interface of MyBatis and assembs it: here is the core of the combination of the two. Through the com.mybatis.dao.UserDao interface, is our “step 3: Create a mapping file corresponding interface “, so this is the core of the integration, the inside of the interfaces specified path basePackage, sqlSessionFactoryBeanName sqlSessionFactory session factory is used.
By now, is it clear? I am comparing MyBatis with the way it is not integrated, so that I know what Spring does for the integration of both.
Step 7: Test the sample
Let’s start with a common test class:
@Controller("userController")
public class UserController {
@Autowired
private UserDao userDao;
public void test(a) {
// Query a user
MyUser auser = userDao.selectUserById(1);
System.out.println(auser);
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = =");
// Query all users
List<MyUser> list = userDao.selectAllUser();
for(MyUser myUser : list) { System.out.println(myUser); }}}Copy the code
Test examples:
// Used to test MyBatis and Spring integration
public class SpringMyBatisTest {
public static void main(String[] args) {
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserController uc = (UserController) applicationContext.getBean("userController"); uc.test(); }}Copy the code
Output result:
MyUser(uid=1, uname= Zhang SAN, USex = female) MyUser(uid=2, uname= Chen, USex = male) MyUser(uid=3, uname= Ouzi, USex = male)Copy the code
The project framework
If you just want to make the project run based on the above example, it is still a little difficult for the small white, because you do not know which file to put where, here I directly give the project view, does it feel super warm.
Afterword.
To learn a tool, we still need to learn from the source of evolution. For example, to learn the integration of MyBatis and Spring Boost, we need to learn the integration of MyBatis and Spring Boost first. Although we know how to use MyBatis, we don’t know how to locate problems, so we still need to master the basic process and principle. Learning annotations, for example, originally evolved from XML, if you do not know XML, directly to learn annotations, then the understanding is not deep.
In MyBatis, I will write about the integration of MyBatis with Spring Boost. After writing the program, I will write this article.
Welcome everyone to like a lot, more articles, please pay attention to the wechat public number “Lou Zai advanced road”, point attention, do not get lost ~~