search
HomeJavajavaTutorialSpring+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><!-- 加载配置文件 --><property-placeholder></property-placeholder><!-- 数据库连接池,使用dbcp --><bean><property></property><property></property><property></property><property></property><property></property><property></property></bean><!-- SqlSessionFactory配置 --><!-- 让Spring管理SqlSessionFactory使用mybatis和spring整合包中的 --><bean><!-- 数据库连接池 --><property></property><!-- 加载mybatis的全局配置文件 --><property></property></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"?>nbsp;mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace命名空间,作用就是对sql进行分类化的管理,理解为sql隔离
    注意:使用mapper代理开发时,namespace有特殊作用  --><mapper><!--在映射文件中配置很多sql语句  --><!--需求:通过id查询用户表的记录  --><!--id:标识映射文件中的sql,称为statement的id。将sql语句封装在mapperStatement的对象中,所有id称为Statement的id;
        parameterType:指定输入参数的类型,这里指定int型;
        #{}:表示一个占位符;
        #{id}:其中id表示接收输入的参数,参数名称就是id,如果输入参数是简单类型,#{}中的参数名可以任意,可以是value或其它名称;
        resultType:指定输出结果所映射的Java对象类型,select指定resultType表示将单条记录映射成Java对象。      --><select>select * from user where id=#{value}</select> </mapper>

Load User.xml in SqlMapConfig.xml


<?xml  version="1.0" encoding="UTF-8"?>nbsp;configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
 <configuration>  <!-- 
      批量别名的定义:
      package:指定包名,mybatis会自动扫描包中的pojo类,自定义别名,别名就是类名(首字母大写或小写都可以) -->  <typealiases>  <package></package>  </typealiases><mappers><mapper></mapper><!-- 批量加载映射配置文件,mybatis自动扫描包下的mapper接口进行加载;
            遵循一定的规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录中;
            以上规范的前提是:使用的是mapper代理方法;          --><package></package></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><property></property></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"?>nbsp;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><select>select * from user where id=#{value}</select></mapper>


public interface UserMapper {public User findUserById(int id) throws Exception;
}
4.2.2 Create proxy object through MapperFactoryBean

Configure mapper in applicationContext.xml.


    <!-- 方法二:mapper配置
         MapperFactoryBean:根据mapper接口生成代理对象     --><bean><property></property><property></property></bean>
4.2.3 Test program


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);
    }
}
The problem with this method: it needs to be configured for each mapper. trouble.

4.3 Mapper scanning through MapperScannerConfigurer (recommended)

Configure mapper batch scanning in applicationContext.xml.


    <!-- 方法三:mapper批量扫描 
          从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
          遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中。
         自动扫描出来的mapper的bean的id为mapper类名(首字母小写)     --><bean><!-- 指定扫描的包名
             如果扫描多个包,每个包中间使用半角逗号分隔          --><property></property><property></property></bean>
At this time, the configuration of mapper for batch loading joanna.yan.mapper in SqlMapConfig.xml can be omitted.

Test procedure:


@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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java之Mybatis的二级缓存怎么使用Java之Mybatis的二级缓存怎么使用May 24, 2023 pm 06:16 PM

缓存的概述和分类概述缓存就是一块内存空间.保存临时数据为什么使用缓存将数据源(数据库或者文件)中的数据读取出来存放到缓存中,再次获取的时候,直接从缓存中获取,可以减少和数据库交互的次数,这样可以提升程序的性能!缓存的适用情况适用于缓存的:经常查询但不经常修改的(eg:省市,类别数据),数据的正确与否对最终结果影响不大的不适用缓存的:经常改变的数据,敏感数据(例如:股市的牌价,银行的汇率,银行卡里面的钱)等等MyBatis缓存类别一级缓存:它是sqlSession对象的缓存,自带的(不需要配置)不

怎么使用springboot+mybatis拦截器实现水平分表怎么使用springboot+mybatis拦截器实现水平分表May 14, 2023 pm 06:43 PM

MyBatis允许使用插件来拦截的方法Executor(update,query,flushStatements,commit,rollback,getTransaction,close,isClosed)ParameterHandler(getParameterObject,setParameters)ResultSetHandler(handleResultSets,handleOutputParameters)StatementHandler(prepare,parameterize,ba

mybatis分页的几种方式mybatis分页的几种方式Jan 04, 2023 pm 04:23 PM

mybatis分页的方式:1、借助数组进行分页,首先查询出全部数据,然后再list中截取需要的部分。2、借助Sql语句进行分页,在sql语句后面添加limit分页语句即可。3、利用拦截器分页,通过拦截器给sql语句末尾加上limit语句来分页查询。4、利用RowBounds实现分页,需要一次获取所有符合条件的数据,然后在内存中对大数据进行操作即可实现分页效果。

springboot怎么整合mybatis分页拦截器springboot怎么整合mybatis分页拦截器May 13, 2023 pm 04:31 PM

简介今天开发时想将自己写好的代码拿来优化,因为不想在开发服弄,怕搞坏了到时候GIT到生产服一大堆问题,然后把它分离到我轮子(工具)项目上,最后运行后发现我获取List的时候很卡至少10秒,我惊了平时也就我的正常版本是800ms左右(不要看它很久,因为数据量很大,也很正常。),前提是我也知道很慢,就等的确需要优化时,我在放出我优化的plus版本,回到10秒哪里,最开始我刚刚接到这个app项目时,在我用PageHelper.startPage(page,num);(分页),还没等查到的数据封装(Pa

mybatis怎么调用mysql存储过程并获取返回值mybatis怎么调用mysql存储过程并获取返回值May 27, 2023 am 09:01 AM

mybatis调用mysql存储过程并获取返回值1、mysql创建存储过程#结束符号默认;,delimiter$$语句表示结束符号变更为$$delimiter$$CREATEPROCEDURE`demo`(INinStrVARCHAR(100),outourStrVARCHAR(4000))BEGINSETourStr=&#39;01&#39;;if(inStr==&#39;02&#39;)thensetourStr=&#39;02&#39;;en

springboot配置mybatis的sql执行超时时间怎么解决springboot配置mybatis的sql执行超时时间怎么解决May 15, 2023 pm 06:10 PM

当某些sql因为不知名原因堵塞时,为了不影响后台服务运行,想要给sql增加执行时间限制,超时后就抛异常,保证后台线程不会因为sql堵塞而堵塞。一、yml全局配置单数据源可以,多数据源时会失效二、java配置类配置成功抛出超时异常。importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;importorg.apache.

PageHelper在springboot+mybatis框架中如何使用PageHelper在springboot+mybatis框架中如何使用May 12, 2023 pm 03:55 PM

一、思路将分页所需的内容都放到一个实体类中分页数据所需要的实体类!内包含页码,页大小,总条数,总页数,起始行pagehelpr提供了这个类pageInfo,不需要我们自己创建二、主要逻辑select*from表名limit起始行,展示几条数据#第n页每页展示五条数据select*from表名limit(n-1)*5,5#每页展示多少条pageSize3#总共有多少条totalselectcount(*)from表名#总页数pagespages=total%pagesSize==0?total/p

SpringBoot怎么打印mybatis的执行sql问题SpringBoot怎么打印mybatis的执行sql问题May 15, 2023 pm 10:55 PM

SpringBoot打印mybatis的执行sql1、使用场景应为在开发过程之中跟踪后端SQL语句,因什么原因导致的错误。需要在Debug过程之中打印出执行的SQL语句。所以需要配置一下SpringBoot之中,Mybatis打印SQL语句。2、具体实现application.properties(yml)中配置的两种方式:1.logging.level.dao包名(daopackage)=debug2.mybatis.configuration.log-impl=org.apache.ibat

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.