mybatis-spring集成完整版

一、项目整体

  1. mybatis接口层、mapper层
  2. Service层
  3. Test调用测试

二、自动生成代码-mybatis generator

  主要修改:

    接口、mapper、实体类的包结构

    需要生成的数据库表

  生成的包目录结构:

三、配置mybatis-config.xml

  1. 配置数据源:安装derby,使用网络模式连接
  2. 映射器
  3. 事务管理器、别名、插件之类
  4. 加级联,mapper.xml和实体类
  5. 配置setting懒加载
  6. 详细配置见--九、mybatis-config.xml

四、整合spring,配置applicationContext.xml

  1. 配置数据源
  2. 配置sqlSessionFactory:DataSource、引入mybatis-config.xml
  3. 自动加载映射文件
  4. 配置自动扫描接口
  5. 开启注解
  6. 详细配置见--九、applicationContext.xml(33-89行)

  【注】此处使用多数据源配置,详见下篇

五、配置注解方式(自动创建bean)

  1. 启动aop注解
  2. service实现类上添加@service,并声明private mapper接口(添加@Autowired)
  3. 测试类上声明service接口(添加@Autowired)
  4. applicationContext.xml配置(16-21行)

User为例:

  接口类:

  1. @Component("USERMAPPER")  //配置自动生成的bean的名字
  2. public interface UserMapper {
  3. 。。。
  4. }

  service实现类

  1. @Service("USERSERVICEIMP")
  2. public class UserServiceImpl implements UserService{
  3. @Autowired
  4. private UserMapper userMapper;
  5. //...
  6. }

  test类

  1. public class UserTest extends SpringTestCase{
  2. @Autowired
  3. private UserService userService;
  4. //...
  5. }

  SpringTestCase类(此类是加载applicationContext.xml文件,可直接写个初始化方法启动加载)

  1. import org.junit.runner.RunWith;
  2. import org.springframework.test.context.ContextConfiguration;
  3. import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
  4. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  5.  
  6. @ContextConfiguration(locations={"classpath:applicationContext.xml"})
  7. @RunWith(SpringJUnit4ClassRunner.class)
  8. public class SpringTestCase extends AbstractJUnit4SpringContextTests{
  9.  
  10. }

六、配置事务

  Xml添加事务管理器配置,开启事务注解(详细配置见applicationContext.xml    91-95行)

  在需要添加事务的方法或类上添加注解:

  @Transactional(value="transactionManager",propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)

  //事务名、传播方式、隔离级别

七、配置ehcache

  1. ApplicationContext.xml:(1)添加cache配置;(2)引入ehcache.xml;(3)开启cache注解;(详细配置见applicationContext.xml  23-31行)
  2. ehcache.xml:配置自定义缓存(需要配置属性)(见 九、ehcache.xml)
  3. 添加cache注解:

    @Cacheable 属性,value、key和condition

    @CachePut  属性,value、key和condition检查相同key的缓存元素

    @CacheEvict 属性value、key、condition、allEntries和beforeInvocation清除缓存元素

  【注】实体类需要序列化,否则写缓存出错

事务+cache运用

  1. @Service("USERSERVICEIMP")
  2. public class UserServiceImpl implements UserService{
  3. @Autowired
  4. private UserMapper userMapper;
  5.  
  6. @Transactional(value="transactionManager",propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)
  7. public void Transaction(){
  8. User user=new User();
  9. user.setId(14);
  10. user.setAccount("admin");
  11. user.setName("管理员");
  12. user.setPassword("123456");
  13. user.setRoleId(1);
  14. int i=userMapper.insert(user);
  15. User user1=new User();
  16. user1.setId(14);
  17. user1.setAccount("admin");
  18. user1.setName("管理员");
  19. user1.setPassword("123456");
  20. user1.setRoleId(2);
  21. int j=userMapper.insert(user1);
  22. System.out.println(i+"--"+j);
  23. }
  24.  
  25. @Cacheable(value="sampleCache",key="#id")
  26. public User selectByPrimaryKey(Integer id) {
  27. User user=userMapper.selectByPrimaryKey(id);
  28. System.out.println(user);
  29. return user;
  30. }
  31.  
  32. @Override
  33. @CacheEvict(value="sampleCache",key="#id",allEntries=true,beforeInvocation=true)
  34. public int updateByPrimaryKeySelective(User record) {
  35. // TODO Auto-generated method stub
  36. int i=userMapper.updateByPrimaryKeySelective(record);
  37. return i;
  38. }
  39.  
  40. }

八、配置log4j、junit4

见 九、配置文件

九、配置文件

  applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:p="http://www.springframework.org/schema/p"
  7. xmlns:tx="http://www.springframework.org/schema/tx"
  8. xmlns:cache="http://www.springframework.org/schema/cache"
  9. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
  11. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
  12. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
  13. http://www.springframework.org/schema/cache
  14. http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">
  15.  
  16. <!-- 启动spring注解 -->
  17. <context:annotation-config/>
  18. <!-- 扫描注解所在的包 -->
  19. <context:component-scan base-package="com.example"/>
  20. <!-- 启动aop注解 -->
  21. <aop:aspectj-autoproxy proxy-target-class="true"/>
  22.  
  23. <!-- cache配置 -->
  24. <cache:annotation-driven cache-manager="cacheManager"/>
  25. <!-- 声明cachemanager -->
  26. <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
  27. <property name="cacheManager" ref="ehcache"></property>
  28. </bean>
  29. <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  30. <property name="configLocation" value="classpath:ehcache.xml"></property>
  31. </bean>
  32.  
  33. <!-- 引入属性文件 -->
  34. <context:property-placeholder location="classpath:jdbc.properties"/>
  35.  
  36. <!-- 配置数据源master -->
  37. <bean id="dataSourceMaster" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  38. <property name="driverClassName" value="${driver}"/>
  39. <property name="url" value="${url}" />
  40. <!-- 初始化连接大小 -->
  41. <property name="initialSize" value="0" />
  42. <!-- 连接池最大使用连接数量 -->
  43. <property name="maxActive" value="20" />
  44. <!-- 连接池最小空闲 -->
  45. <property name="minIdle" value="1" />
  46. <!-- 连接池最大空闲 -->
  47. <property name="maxIdle" value="20" />
  48. <!-- 获取连接最大等待时间 -->
  49. <property name="maxWait" value="60000" />
  50. </bean>
  51. <!-- 配置数据源master -->
  52. <bean id="dataSourceSlave" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
  53. <property name="driverClassName" value="${driver}"/>
  54. <property name="url" value="${url_slave}" />
  55. <!-- 初始化连接大小 -->
  56. <property name="initialSize" value="0" />
  57. <!-- 连接池最大使用连接数量 -->
  58. <property name="maxActive" value="20" />
  59. <!-- 连接池最小空闲 -->
  60. <property name="minIdle" value="0" />
  61. <!-- 连接池最大空闲 -->
  62. <property name="maxIdle" value="20" />
  63. <!-- 获取连接最大等待时间 -->
  64. <property name="maxWait" value="60000" />
  65. </bean>
  66. <bean id="dataSource" class="com.example.util.ThreadLocalRountingDataSource">
  67. <property name="targetDataSources">
  68. <map key-type="com.example.enums.DataSources">
  69. <entry key="MASTER" value-ref="dataSourceMaster" />
  70. <entry key="SLAVE" value-ref="dataSourceSlave"/>
  71. </map>
  72. </property>
  73. <property name="defaultTargetDataSource" ref="dataSourceMaster"></property>
  74.  
  75. </bean>
  76.  
  77. <!-- 配置SQLSessionFactory -->
  78. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  79. <property name="dataSource" ref="dataSource"/>
  80. <property name="configLocation" value="classpath:mybatis-config.xml"></property>
  81. <!-- 加载映射文件 -->
  82. <property name="mapperLocations" value="classpath*:/com/example/dao/*Mapper.xml"></property>
  83. </bean>
  84.  
  85. <!-- 接口方式 -->
  86. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  87. <property name="basePackage" value="com.example.dao"></property>
  88. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
  89. </bean>
  90.  
  91. <!-- 配置jdbc事务管理器,完成数据的完整性和一致性 -->
  92. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  93. <property name="dataSource" ref="dataSource"></property>
  94. </bean>
  95. <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
  96.  
  97. </beans>

  jdbc.properties

  1. driver=org.apache.derby.jdbc.ClientDriver
  2. url=jdbc:derby://localhost:1527/E:/my/derby/mydb
  3. url_slave=jdbc:derby:E://shiny/DdlUtils-test/mydb

  mybatis.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <!-- 开启延迟加载 -->
  8. <setting name="lazyLoadingEnabled" value="true"/>
  9. <!-- 每种属性按需加载 -->
  10. <setting name="aggressiveLazyLoading" value="false"/>
  11. </settings>
  12.  
  13. </configuration>

  ehcache.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
  4. updateCheck="false">
  5.  
  6. <!-- 指定一个文件目录,当EhCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
  7. <diskStore path="java.io.tempdir"/>
  8.  
  9. <!-- 设定缓存的默认数据过期策略 -->
  10. <defaultCache
  11. maxElementsInMemory="10000"
  12. eternal="false"
  13. overflowToDisk="true"
  14. timeToIdleSeconds="10"
  15. timeToLiveSeconds="20"
  16. diskPersistent="false"
  17. diskExpiryThreadIntervalSeconds="120"/>
  18.  
  19. <cache name="sampleCache" maxElementsInMemory="1000" eternal="false" overflowToDisk="true" diskSpoolBufferSizeMB="20"
  20. timeToIdleSeconds="1"
  21. timeToLiveSeconds="2" memoryStoreEvictionPolicy="LFU"/>
  22. <cache name="Test" maxElementsInMemory="1" eternal="false" overflowToDisk="true" timeToIdleSeconds="1" timeToLiveSeconds="2"
  23. diskPersistent="false" diskExpiryThreadIntervalSeconds="1" memoryStoreEvictionPolicy="LFU">
  24.  
  25. </cache>
  26.  
  27. </ehcache>

  log4j.properties

  1. log4j.rootLogger=DEBUG, stdout
  2. log4j.logger.org.mybatis=DEBUG
  3. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  4. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  5. log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

(六)mybatis-spring集成完整版的更多相关文章

  1. Spring boot Mybatis 整合(完整版)

    个人开源项目 springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页.个人作品.个人博客) 朋友自制的springboot接口文档组件swagge ...

  2. MyBatis 文档 完整版

    框架技术 1.框架技术 01.是一个应用程序的半成品 02.提供可重用的公共结构 03.按一定规则组织的一组组件 2.分析优势 01.不用再考虑公共问题 02.专心的业务实现上 03.结构统一,易于学 ...

  3. Spring MVC 学习总结(六)——Spring+Spring MVC+MyBatis框架集成

    与SSH(Struts/Spring/Hibernate/)一样,Spring+SpringMVC+MyBatis也有一个简称SSM,Spring实现业务对象管理,Spring MVC负责请求的转发和 ...

  4. 【ELK】4.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版+kibana管理ES的index操作

    spring boot 2.X集成ES 进行CRUD操作  完整版 内容包括: ============================================================ ...

  5. SSM Spring SpringMVC Mybatis框架整合Java配置完整版

    以前用着SSH都是老师给配好的,自己直接改就可以.但是公司主流还是SSM,就自己研究了一下Java版本的配置.网上大多是基于xnl的配置,但是越往后越新的项目都开始基于JavaConfig配置了,这也 ...

  6. Spring boot 整合 Mybatis (完整版)

    最近工作上时间有点多,然后自己就学习了一下Spring boot,外加上Mybatis,在实际开发中都是比较常用的,所以这篇写一下SpringBoot整合Mybatis. 一.数据准备 CREATE ...

  7. spring boot+mybatis+quartz项目的搭建完整版

    1. 利用spring boot提供的工具(http://start.spring.io/)自动生成一个标准的spring boot项目架构 2. 因为这里我们是搭建spring boot+mybat ...

  8. Spring+Spring MVC+MyBatis框架集成

    目录 一.新建一个基于Maven的Web项目 二.创建数据库与表 三.添加依赖包 四.新建POJO实体层 五.新建MyBatis SQL映射层 六.JUnit测试数据访问 七.完成Spring整合My ...

  9. Spring MVC 学习总结(十)——Spring+Spring MVC+MyBatis框架集成(IntelliJ IDEA SSM集成)

    与SSH(Struts/Spring/Hibernate/)一样,Spring+SpringMVC+MyBatis也有一个简称SSM,Spring实现业务对象管理,Spring MVC负责请求的转发和 ...

随机推荐

  1. cisco路由器license的相关命令简单梳理(转)

    转自https://blog.51cto.com/legendland/1900185作者:legendlandlicense:对于IP Base基本的IOS功能外,另外三个技术包(1 数据Data: ...

  2. python加速

    之前一直用 conda版python, 发现可以直接装intel的numpy了. https://software.intel.com/en-us/articles/installing-the-in ...

  3. 吴裕雄--天生自然ShellX学习笔记:Shell test 命令

    Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值.字符和文件三个方面的测试. 实例演示: num1=100 num2=100 if test $[num1] -eq $[num2 ...

  4. java和数据库中所有的锁都在这了

    1.java中的锁 1.1 锁的种类 公平锁/非公平锁 可重入锁/不可重入 独享锁/共享锁 读写锁 分段锁 偏向锁/轻量级锁/重量级锁 自旋锁 1.2 锁详细介绍 1.2.1 公平锁,非公平锁 公平锁 ...

  5. python语法基础-并发编程-进程-其他

    ###############    多进程的信号量    ############## # 多进程的信号量 from multiprocessing import Process import ti ...

  6. Linux 笔记(自用)

    一,常用工具 1. 常用浏览器 w3m links lynx 都可以用 apt-get install *** 安装,访问方式都是 w3m/links/lynx www.baidu.com 的形式 2 ...

  7. Insulator|enhancer|LCR|EKLF|CTCF|调控基因印记| A-USF|HATs|ChIP|Chip-seq|PAGE|

    表观遗传学 转录因子 基本转录因子:TFIID.A.B.F.E.H. Pol II… 基转录因子具有稳定作用 组织特异性转录因子:GATA.EKLF.Bcl11A… 特异性是在特定组织中的细胞中时与细 ...

  8. 第二季第十天 es6新特性新特性

    1.set的应用(去重)js标准内置对象 适用范围:String,Array(数字基本数据类型不可以) set的方法:例子 var s = new Set(data) 增加:  s.add(data) ...

  9. sol - 0x63

    [例题]巡逻 注意到K只能是1或2,也就是说只能建0/1/2条新道路 我们分类讨论 当修建0条新道路的时候, 执行遍历会恰好遍历到每条边2次,答案为2*(n-1) 当修建1条新道路的时候, 我们设新道 ...

  10. JavaScript 的 URL 对象是什么?

    如果我们自己编写从URL中分析和提取元素的代码,那么有可能会比较痛苦和麻烦.程序员作为这个社会中最“懒”的群体之一,无休止的重复造轮子必然是令人难以容忍的,所以大多数浏览器的标准库中都已经内置了URL ...