(六)mybatis-spring集成完整版

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为例:

  接口类:

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

  service实现类

@Service("USERSERVICEIMP")
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    //...
}

  test类

public class UserTest extends SpringTestCase{
    @Autowired
    private UserService userService;
    //...
}

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

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations={"classpath:applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringTestCase extends AbstractJUnit4SpringContextTests{

}

六、配置事务

  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运用

@Service("USERSERVICEIMP")
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Transactional(value="transactionManager",propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)
    public void Transaction(){
        User user=new User();
        user.setId(14);
        user.setAccount("admin");
        user.setName("管理员");
        user.setPassword("123456");
        user.setRoleId(1);
        int i=userMapper.insert(user);
        User user1=new User();
        user1.setId(14);
        user1.setAccount("admin");
        user1.setName("管理员");
        user1.setPassword("123456");
        user1.setRoleId(2);
        int j=userMapper.insert(user1);
        System.out.println(i+"--"+j);
    }
    
    @Cacheable(value="sampleCache",key="#id")
    public User selectByPrimaryKey(Integer id) {
        User user=userMapper.selectByPrimaryKey(id);
        System.out.println(user);
        return user;
    }

    @Override
    @CacheEvict(value="sampleCache",key="#id",allEntries=true,beforeInvocation=true)
    public int updateByPrimaryKeySelective(User record) {
        // TODO Auto-generated method stub
        int i=userMapper.updateByPrimaryKeySelective(record);
        return i;
    }

}

八、配置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

driver=org.apache.derby.jdbc.ClientDriver
url=jdbc:derby://localhost:1527/E:/my/derby/mydb
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

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

 

 

 

 

posted @ 2018-01-15 15:12  Together~  阅读(275)  评论(0编辑  收藏  举报