


Spring+SpringMVC+MyBatis in-depth learning and construction-MyBatis and Spring integration
Please indicate the source for reprinting:
As mentioned earlier: Spring+SpringMVC+MyBatis in-depth learning and construction (8)-MyBatis query cache
1. Integration ideas
Spring is required to manage SqlSessionFactory through a single instance.
Spring and MyBatis integrate to generate proxy objects, and use SqlSessionFactory to create SqlSession. (The integration of Spring and MyBatis is automatically completed)
The mappers of the persistence layer need to be managed by Spring.
2. Integrated environment
Create a java project (close to the actual development project structure)
jar package:
mybatis3.2.7 jar package
jar package of spring3.2.0
dbcp connection pool
Database driver
Integration package of mybatis and spring: The early integration of ibatis and spring was officially launched by spring Provided, mybatis and spring integration are provided by mybatis.
3.spring configuration file
Configure sqlSessionFactory and data source in applicationContext.xml. SqlSessionFactory is under the integration package of mybatis and spring.
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans "><!-- 加载配置文件 --><context:property-placeholder location="classpath:db.properties"/><!-- 数据库连接池,使用dbcp --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><property name="maxActive" value="10"/><property name="maxIdle" value="5"/></bean><!-- SqlSessionFactory配置 --><!-- 让Spring管理SqlSessionFactory使用mybatis和spring整合包中的 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 数据库连接池 --><property name="dataSource" ref="dataSource" /><!-- 加载mybatis的全局配置文件 --><property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /></bean></beans>
4. Three methods written by Mapper
4.1 Original dao development (after integration with spring)
4.1.1User. xml
<?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"><!--namespace命名空间,作用就是对sql进行分类化的管理,理解为sql隔离 注意:使用mapper代理开发时,namespace有特殊作用 --><mapper namespace="test"><!--在映射文件中配置很多sql语句 --><!--需求:通过id查询用户表的记录 --><!--id:标识映射文件中的sql,称为statement的id。将sql语句封装在mapperStatement的对象中,所有id称为Statement的id; parameterType:指定输入参数的类型,这里指定int型; #{}:表示一个占位符; #{id}:其中id表示接收输入的参数,参数名称就是id,如果输入参数是简单类型,#{}中的参数名可以任意,可以是value或其它名称; resultType:指定输出结果所映射的Java对象类型,select指定resultType表示将单条记录映射成Java对象。 --><select id="findUserById" parameterType="int" resultType="joanna.yan.po.User">select * from user where id=#{value}</select> </mapper>
Load User.xml in SqlMapConfig.xml
<?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> <!-- 批量别名的定义: package:指定包名,mybatis会自动扫描包中的pojo类,自定义别名,别名就是类名(首字母大写或小写都可以) --> <typeAliases> <package name="joanna.yan.po"/> </typeAliases><mappers><mapper resource="sqlmap/User.xml"/><!-- 批量加载映射配置文件,mybatis自动扫描包下的mapper接口进行加载; 遵循一定的规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录中; 以上规范的前提是:使用的是mapper代理方法; --><package name="joanna.yan.mapper"/></mappers> </configuration>
4.1.2 dao (implement class inheritance SqlSessionDaoSupport)
public interface UserDao {//根据id查询用户信息public User findUserById(int id) throws Exception; }
dao interface implementation class needs to inject SqlSessionFactory through spring.
The spring declaration configuration method is used here to configure the dao bean: Let the UserDaoImpl implementation class inherit SqlSessionDaoSupport.
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{ @Overridepublic User findUserById(int id) throws Exception {//继承SqlSessionDaoSupport,通过this.getSqlSession()得到sqlSessionSqlSession sqlSession=this.getSqlSession(); User user=sqlSession.selectOne("test.findUserById", id);return user; } }
4.1.3 Configure dao
Configure dao in applicationContext.xml.
<!-- 方法一:原始dao接口 --><bean id="userDao" class="joanna.yan.dao.UserDaoImpl"><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean>
4.1.4 Test program
public class UserDaoImplTest {private ApplicationContext applicationContext; @Beforepublic void setUp(){ applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); } @Testpublic void findUsetByIdTest() throws Exception{ UserDao userDao=(UserDao) applicationContext.getBean("userDao"); User user=userDao.findUserById(1); System.out.println(user); } }
4.2mapper agent development
4.2.1mapper .xml and mapper.java
##
<?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"><!--namespace命名空间,作用就是对sql进行分类化的管理,理解为sql隔离 注意:使用mapper代理开发时,namespace有特殊作用,namespace等于mapper接口地址 --><mapper namespace="joanna.yan.mapper.UserMapper"><select id="findUserById" parameterType="int" resultType="user">select * from user where id=#{value}</select></mapper>
public interface UserMapper {public User findUserById(int id) throws Exception; }
<!-- 方法二:mapper配置 MapperFactoryBean:根据mapper接口生成代理对象 --><bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="mapperInterface" value="joanna.yan.mapper.UserMapper" /><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean>
public class UserMapperTest {private ApplicationContext applicationContext; @Beforepublic void setUp(){ applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); } @Testpublic void findUsetByIdTest() throws Exception{ UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper"); User user=userMapper.findUserById(1); System.out.println(user); } }
<!-- 方法三:mapper批量扫描 从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册 遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中。 自动扫描出来的mapper的bean的id为mapper类名(首字母小写) --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 指定扫描的包名 如果扫描多个包,每个包中间使用半角逗号分隔 --><property name="basePackage" value="joanna.yan.mapper"/><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean>
@Testpublic void findUsetByIdTest() throws Exception{ UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper"); User user=userMapper.findUserById(1); System.out.println(user); }
The above is the detailed content of Spring+SpringMVC+MyBatis in-depth learning and construction-MyBatis and Spring integration. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

Players can collect different materials to build buildings when playing in the Mistlock Kingdom. Many players want to know whether to build buildings in the wild. Buildings cannot be built in the wild in the Mistlock Kingdom. They must be within the scope of the altar. . Can buildings be built in the wild in Mistlock Kingdom? Answer: No. 1. Buildings cannot be built in the wild areas of the Mist Lock Kingdom. 2. The building must be built within the scope of the altar. 3. Players can place the Spirit Fire Altar by themselves, but once they leave the range, they will not be able to construct buildings. 4. We can also directly dig a hole in the mountain as our home, so we don’t need to consume building materials. 5. There is a comfort mechanism in the buildings built by players themselves, that is to say, the better the interior, the higher the comfort. 6. High comfort will bring attribute bonuses to players, such as

Title: Learn the main function in Go language from scratch. As a simple and efficient programming language, Go language is favored by developers. In the Go language, the main function is an entry function, and every Go program must contain the main function as the entry point of the program. This article will introduce how to learn the main function in Go language from scratch and provide specific code examples. 1. First, we need to install the Go language development environment. You can go to the official website (https://golang.org

MyBatis is a popular persistence layer framework that provides convenient SQL mapping and database operation functions, allowing developers to interact with the database more efficiently. In the actual development process, we sometimes need to print out the SQL statements executed by MyBatis on the console in real time to better debug and optimize SQL queries. This article will introduce how to realize real-time printing of SQL on the console in MyBatis and provide specific code examples. First, we need to add My

PyTorch Installation Guide: Quickly set up a development environment in PyCharm PyTorch is one of the most popular frameworks in the current field of deep learning. It has the characteristics of ease of use and flexibility, and is favored by developers. This article will introduce how to quickly set up the PyTorch development environment in PyCharm, so that you can start the development of deep learning projects. Step 1: Install PyTorch First, we need to install PyTorch. The installation of PyTorch usually needs to take into account the system environment
