单独使用mybatis是有很多限制的(比如无法实现跨越多个session的事务),而且很多业务系统本来就是使用spring来管理的事务,因此mybatis最好与spring集成起来使用。 前置要求 版本要求 项目 版本 下载地址 说明 mybatis 3.0及以上 https://github.com/mybati
单独使用mybatis是有很多限制的(比如无法实现跨越多个session的事务),而且很多业务系统本来就是使用spring来管理的事务,因此mybatis最好与spring集成起来使用。
前置要求
版本要求
项目 |
版本 |
下载地址 |
说明 |
mybatis |
3.0及以上 |
https://github.com/mybatis/mybatis-3/releases |
|
spring |
3.0及以上 |
http://projects.spring.io/spring-framework/ |
|
mybatis-spring |
1.0及以上 |
https://github.com/mybatis/spring/releases |
|
spring事务配置
<!-- 自动扫描业务包 --> <context:component-scan base-package="com.xxx.service" /> <!-- 数据源 --> <jee:jndi-lookup id="jndiDataSource" jndi-name="java:comp/env/jdbc/datasource" /> <!-- 配置事务 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="jndiDataSource" /> </bean> <!-- 配置基于注解的事物aop --> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
单个集成
<!-- 集成mybatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="jndiDataSource" /> <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" /> <!-- 自动配置别名 --> <property name="typeAliasesPackage" value="com.xxx.dto" /> </bean> <!--创建dao bean(只需提供接口不需提供实现类 )--> <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.xxx.dao.UserDao" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
我们不但要明白如何使用,更要明白为什么要这么使用。
SqlSessionFactoryBean是一个工厂bean,它的作用就是解析配置(数据源、别名等)。
MapperFactoryBean是一个工厂bean,在spring容器里,工厂bean是有特殊用途的,当spring将工厂bean注入到其他bean里时,它不是注入工厂bean本身而是调用bean的getObject方法。我们接下来就看看这个getObjec方法干了些什么:
public T getObject() throws Exception { return getSqlSession().getMapper(this.mapperInterface); }
看到这里大家应该就很明白了,这个方法和我们之前单独使用Mybatis的方式是一样的,都是先获取一个Sqlsession对象,然后再从Sqlsession里获取Mapper对象(再次强调Mapper是一个代理对象,它代理的是mapperInterface接口,而这个接口是用户提供的dao接口)。自然,最终注入到业务层就是这个Mapper对象。
实际的项目一般来说不止一个Dao,如果你有多个Dao那就按照上面的配置依次配置即可。
如何使用批量更新
前一节讲了如何注入一个mapper对象到业务层, mapper的行为依赖于配置,mybatis默认使用单个更新(即ExecutorType默认为SIMPLE而不是BATCH),当然我们可以通过修改mybatis配置文件来修改默认行为,但如果我们只想让某个或某几个mapper使用批量更新就不得行了。这个时候我们就需要使用模板技术:
<!--通过模板定制mybatis的行为 --> <bean id="sqlSessionTemplateSimple" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <!--更新采用单个模式 --> <constructor-arg index="1" value="SIMPLE"/> </bean> <!--通过模板定制mybatis的行为 --> <bean id="sqlSessionTemplateBatch" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <!--更新采用批量模式 --> <constructor-arg index="1" value="BATCH"/> </bean>
这里笔者定义了两个模板对象,一个使用单个更新,一个使用批量更新。有了模板之后我们就可以改变mapper的行为方式了:
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.xxx.dao.UserDao" /> <property name="sqlSessionTemplate" ref=" sqlSessionTemplateBatch " /> </bean>
跟上一节的mapper配置不同的是,这里不需要配置sqlSessionFactory属性,只需要配置sqlSessionTemplate(sqlSessionFactory属性在模板里已经配置好了)。
通过自动扫描简化mapper的配置
前面的章节可以看到,我们的dao需要一个一个的配置在配置文件中,如果有很多个dao的话配置文件就会非常大,这样管理起来就会比较痛苦。幸好mybatis团队也意识到了这点,他们利用spring提供的自动扫描功能封装了一个自动扫描dao的工具类,这样我们就可以使用这个功能简化配置:
<!-- 采用自动扫描方式创建mapper bean(单个更新模式) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xxx.dao" /> <property name="sqlSessionTemplateBeanName" value="sqlSessionTemplateSimple" /> <property name="markerInterface" value="com.xxx.dao.SimpleDao" /> </bean> <!-- 采用自动扫描方式创建mapper bean(批量更新模式) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xxx.dao" /> <property name="sqlSessionTemplateBeanName" value="sqlSessionTemplateBatch" /> <property name="markerInterface" value="com.xxx.dao.BatchDao" /> </bean>
MapperScannerConfigurer本身涉及的spring的技术我就不多讲了,感兴趣且对spring原理比较了解的可以去看下它的源码。我们重点看一下它的三个属性:
basePackage:扫描器开始扫描的基础包名,支持嵌套扫描;
sqlSessionTemplateBeanName:前文提到的模板bean的名称;
markerInterface:基于接口的过滤器,实现了该接口的dao才会被扫描器扫描,与basePackage是与的作用。
除了使用接口过滤外,还可使用注解过滤:
<!-- 采用自动扫描方式创建mapper bean(批量更新模式) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.xxx.dao" /> <property name="sqlSessionTemplateBeanName" value="sqlSessionTemplateBatch" /> <property name="annotationClass" value="com.xxx.dao.BatchAnnotation" /> </bean>
annotationClass:配置了该注解的dao才会被扫描器扫描,与basePackage是与的作用。
需要注意的是,两个过滤条件只能配一个。

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.