Spring整合MyBatis框架
admin
2024-03-25 23:30:38
0

Spring整合MyBatis

Spring整合任何第三方资源套路基本一致。
Spring是一个对象容器

  1. 将第三方资源需要的对象注册在Spring容器中
  2. 将第三方资源的资源文件,交给Spring管理
  3. 所有第三方资源需要的内容全部从Spring中获取

整合MyBatis应该交给Spring的对象是?
SqlSessionFactoryBuilder(临时对象),
SqlSessionFactory(单例),
SqlSession,Mapper

整合

添加依赖

org.springframeworkspring-context5.3.15org.springframeworkspring-jdbc5.2.9.RELEASEmysqlmysql-connector-java5.1.46org.mybatismybatis3.5.6junitjunit4.13test

添加一个中间依赖

    org.mybatismybatis-spring2.0.4

将数据源交给Spring管理,德鲁伊连接池,所谓配置连接池,就是配置一个数据源对象

添加druid的依赖

    com.alibabadruid1.1.10

在spring的配置文件中,解注册一个Druid的数据源
配置文件:




或者利用注解配置:

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;import javax.sql.DataSource;@Configuration
@PropertySource(value = "config/db.properties")
public class DataSourceConfig {@Beanpublic DataSource dataSource(){return new DruidDataSource();}
}

其中配置文件resource/config/db.properties格式如下:

druid.url=jdbc:mysql://ip:3306/test?useUnicode=true&characterEncoding=UTF-8
druid.driver=com.mysql.jdbc.Driver
druid.username=username
druid.password=password

将SqlSessionFactory交给Spring管理
将MyBatis完全托管给Spring,所以MyBatis配置文件中的所有内容全部删除,只留根节点:




在Spring的配置文件中注册一个SqlSessionFactory

    

测试类

    @Testpublic void test(){ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");SqlSessionFactory sqlSessionFactory=ac.getBean(SqlSessionFactory.class);SqlSession sqlSession=sqlSessionFactory.openSession();List objects=sqlSession.selectList("org.example.repository.UserRepository.findAll");System.out.println(objects);}
 

代理mapper的配置
MyBatis可以根据接口生成代理Mapper,Spring整合MyBatis之后一样可以生成代理Mapper,

定义Mapper接口

public interface UserRepository {public List findAll();
}

给这个Mapper接口接口写一个对应的配置文件
配置文件中的namespace必须和Mapper接口的全限定类名一致,将配置文件与Mapper接口放在同一个包中





修改SqlSessionFactory中的映射文件的配置内容

    

测试类

    @Testpublic void test(){ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");//从容器中获取对应的Mapper接口对象UserRepository userRepository=ac.getBean(UserRepository.class);List users=userRepository.findAll();System.out.println(users);}

代理Mapper注意的几个细节

  1. mapper接口和mapper映射文件在一个包
  2. namespace必须和mapper接口的全限定类名
  3. mapper接口中的每个方法在mapper映射文件中都必须有对应的sql语句,sql语句的id必须和mapper接口中方法名一致

maven生成的执行文件中没有对应的映射文件会报错,原因是maven的工程结构中默认所有的资源文件(.properties,xml,ymal)等都是在src/main/resources下,所以当资源文件存在于src/main/java下时,maven不会将这些文件打包到输出目录中

调整方法:在pom.xml中加入

    src/main/java**/*.xmlsrc/main/resources**/*

注解方式配置

添加一个著配置类 AppConfig

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration
@ComponentScan("org.example")
@MapperScan("org.example.repository")//配置映射文件和接口所在的包
public class AppConfig {
}

DataSource和SqlSessionFactory

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;import javax.sql.DataSource;@Configuration
@PropertySource(value = "config/db.properties")
public class DataSourceConfig {@Value("${druid.username}")private String username;@Value("${druid.password}")private String password;@Value("${druid.url}")private String url;@Value("${druid.driver}")private String driverClassName;@Beanpublic DataSource dataSource(){DruidDataSource dataSource=new DruidDataSource();dataSource.setUsername(username);dataSource.setPassword(password);dataSource.setUrl(url);dataSource.setDriverClassName(driverClassName);return dataSource;}@Beanpublic SqlSessionFactory sqlSessionFactory() throws Exception{SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource());sqlSessionFactoryBean.setTypeHandlersPackage("org.example.entity");return sqlSessionFactoryBean.getObject();}
}

测试类

    @Testpublic void test(){ApplicationContext ac=new AnnotationConfigApplicationContext(AppConfig.class);UserRepository userRepository=ac.getBean(UserRepository.class);System.out.println(userRepository.findAll());}

相关内容

热门资讯

河南夫妇冒雨移开折断大树,“不... 评论员 陈柯旭 折断的大树能挡住马路,但挡不住普通人身上的微光。 近日,在河南驻马店突降暴雨,一棵大...
现货黄金跌破4300美元关口 8日,现货黄金盘中跳水,跌破4300美元/盎司,跌超0.6%。 消息面上,据新华社,当地时间7日晚,...
英法德联合出手! 文丨陆弃 当英国首相斯塔默、法国总统马克龙和德国总理默茨准备与乌克兰总统泽连斯基在伦敦举行会晤时,外...
两个月来伊以首次互袭,特朗普想... 当地时间6月7日,伊朗向以色列发射了四轮导弹袭击,以回应数小时前以色列对黎巴嫩首都贝鲁特进行的致命空...
德韩竞标谁能赢? 崔轶亮:难分... 加拿大正在推进“巡逻潜艇项目”,计划采购最多12艘柴电潜艇,以替换预计于2030年代中期退役的4艘“...
向以色列发射三波导弹后,伊朗威... 据参考消息6月8日报道,6月7日晚,伊朗向以色列发射三波导弹,以回应以色列不断升级对黎巴嫩的军事行动...
原创 恐... 6月8日,国际足坛再次出现球员在比赛中昏迷的情况。在丹麦同乌克兰的热身赛中,34岁的埃里克森忽然晕倒...
原创 歼... 这两天,咱们国产隐身机歼-35的外贸版(也就是歼-35AE)算是彻底曝光了,连带着那架编号0001的...
以色列遭多波导弹袭击!特朗普:... 据美国有线电视新闻网(CNN)报道,当地时间7日,伊朗伊斯兰革命卫队(IRGC)发布声明称,当日用弹...
原创 W... WB集团的Warmate“滞留弹药,配备气动弹射器,起飞前使用。(WB集团) 波兰军备局与WB集团签...