MyBatis初学笔记

1、在SqlMapConfig.xml中配置数据链接池,使用连接池管理数据库链接

 1 <!-- 加载属性文件 -->
 2 <properties resource="db.properties">
 3     <!--properties中还可以配置一些属性名和属性值  -->
 4     <!-- <property name="jdbc.driver" value=""/> -->
 5 </properties>
 6 <!-- 和spring整合后 environments配置将废除-->
 7 <environments default="development">
 8     <environment id="development">
 9     <!-- 使用jdbc事务管理,事务控制由mybatis-->
10         <transactionManager type="JDBC" />
11     <!-- 数据库连接池,由mybatis管理-->
12         <dataSource type="POOLED">
13             <property name="driver" value="${jdbc.driver}" />
14             <property name="url" value="${jdbc.url}" />
15             <property name="username" value="${jdbc.username}" />
16             <property name="password" value="${jdbc.password}" />
17         </dataSource>
18     </environment>
19 </environments>

2、将Sql语句配置在XXXXmapper.xml文件中与java代码分离,需将接口类名和映射文件名要一致,且在同一个目录下。并在SqlMapConfig.xml中加载映射文件:
SqlMapConfig.xml:

 1 <!-- 加载 映射文件 -->
 2 <mappers>
 3     <mapper resource="sqlmap/User.xml"/>
 4     <!--通过resource方法一次加载一个映射文件 -->
 5     <!-- <mapper resource="mapper/UserMapper.xml"/> -->
 6     <!-- 通过mapper接口加载单个 映射文件
 7     遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
 8     上边规范的前提是:使用的是mapper代理方法
 9      -->
10     <!-- <mapper class="cn.luswei.mybatis.mapper.UserMapper"/> -->
11     <!-- 批量加载mapper指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载
12     遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
13     上边规范的前提是:使用的是mapper代理方法
14      -->
15     <package name="cn.luswei.mybatis.mapper"/>
16 </mappers>

UserMapper.xml:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
 6 注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace等于mapper接口地址
 7 -->
 8 <mapper namespace="cn.luswei.mybatis.mapper.UserMapper">
 9    <!-- 在 映射文件中配置很多sql语句 -->
10     <!-- 需求:通过id查询用户表的记录 -->
11     <!-- 通过 select执行数据库查询
12     id:标识 映射文件中的 sql
13     将sql语句封装到mappedStatement对象中,所以将id称为statement的id
14     parameterType:指定输入 参数的类型,这里指定int型 
15     #{}表示一个占位符号
16     #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称
17     resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。
18      -->
19     <select id="findUserById" parameterType="int" resultType="user">
20         SELECT * FROM USER WHERE id=#{value}
21     </select>
22    <!-- 根据用户名称模糊查询用户信息,可能返回多条
23     resultType:指定就是单条记录所映射的java对象 类型
24     ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。
25     使用${}拼接sql,引起 sql注入
26     ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value
27      -->
28     <select id="findUserByName" parameterType="java.lang.String" resultType="cn.luswei.mybatis.po.User">
29         SELECT * FROM USER WHERE username LIKE '%${value}%'
30     </select>
31    <!-- 定义resultMap
32     将SELECT id id_,username username_ FROM USER 和User类中的属性作一个映射关系
33     type:resultMap最终映射的java对象类型,可以使用别名
34     id:对resultMap的唯一标识
35     -->
36     <resultMap type="user" id="userResultMap">
37          <!-- id表示查询结果集中唯一标识 
38          column:查询出来的列名
39          property:type指定的pojo类型中的属性名
40          最终resultMap对column和property作一个映射关系 (对应关系)
41          -->
42          <id column="id_" property="id"/>
43          <!-- 
44          result:对普通名映射定义
45          column:查询出来的列名
46          property:type指定的pojo类型中的属性名
47          最终resultMap对column和property作一个映射关系 (对应关系)
48           -->
49          <result column="username_" property="username"/>
50      
51     </resultMap>
52    <!-- 使用resultMap进行输出映射
53     resultMap:指定定义的resultMap的id,如果这个resultMap在其它的mapper文件,前边需要加namespace
54     -->
55     <select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">
56         SELECT id id_,username username_ FROM USER WHERE id=#{value}
57     </select>
58 </mapper>

3、#{}、${}、parameterType、resultType
  #{}:表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换,#{}可以有效防止sql注入。 #{}可以接收简单类型值或pojo属性值。 如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。

  ${}:表示拼接sql串,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, ${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。

  parameterType:指定输入参数类型,mybatis通过ognl从输入对象中获取参数值拼接在sql中。

  resultType:指定输出结果类型,mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。

4、Mapper动态代理方式
Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

Mapper接口开发需要遵循以下规范:

  1、Mapper.xml文件中的namespace与mapper接口的类路径相同。
  2、Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
  3、Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
  4、Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

映射文件Mapper.xml: 定义mapper映射文件UserMapper.xml(内容同Users.xml),需要修改namespace的值为 UserMapper接口路径。将UserMapper.xml放在classpath 下mapper目录 下。

接口文件Mapper.java:
  1、Mapper接口方法名和Mapper.xml中定义的statement的id相同
  2、Mapper接口方法的输入参数类型和mapper.xml中定义的statement的parameterType的类型相同
  3、Mapper接口方法的输出参数类型和mapper.xml中定义的statement的resultType的类型相同

5、程序的测试:

 1     //会话工厂
 2     private SqlSessionFactory sqlSessionFactory;
 3  
 4     @Before
 5     public void createSqlSessionFactory() throws IOException {
 6         // 配置文件
 7         String resource = "SqlMapConfig.xml";
 8         InputStream inputStream = Resources.getResourceAsStream(resource);
 9  
10         // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
11         sqlSessionFactory = new SqlSessionFactoryBuilder()
12                 .build(inputStream);
13  
14     }
15     @Test
16     public void testFindUserById() throws Exception {
17         //获取session
18         SqlSession session = sqlSessionFactory.openSession();
19         //获取mapper接口的代理对象
20         UserMapper userMapper = session.getMapper(UserMapper.class);
21         //调用代理对象方法
22         User user = userMapper.findUserById(1);
23         System.out.println(user);
24         //关闭session
25         session.close();
26     }

6、MyBatis与Spring整合:

jar包:MyBatis官方提供的MyBatis与Spring整合的jar包:mybatis-spring-1.2.2.jar
还包括其他的包:spring相关的包、数据库驱动包、mybatis的包

MyBatis配置文件:

  在classpath下创建mybatis/SqlMapConfig.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         <!-- 全局setting配置,根据需要添加 -->
 7         <!-- 配置别名 -->
 8         <typeAliases>
 9             <!-- 批量扫描别名 -->
10             <package name="cn.luswei.ssm.po"/>
11         </typeAliases>
12      
13         <!-- 配置mapper
14         使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers
15         由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
16         必须遵循:mapper.xml和mapper.java文件同名且在一个目录 
17          -->
18         <!--
19         <mappers>
20         <package name="cn.luswei.mybatis.mapper" />
21         </mappers>
22          -->
23     </configuration>

  在spring配置文件中定义一个Mapper扫描器,自动扫描包中的Mapper接口生成代理对象:此方法即mapper接口开发方法,只需定义mapper接口,不用编写mapper接口实现类。只需要在spring配置文件中定义一个mapper扫描器,自动扫描包中的mapper接口生成代代理对象,如:

1     <!-- mapper扫描器
2         mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册 
3         遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录 中
4         自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
5      -->
6     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
7         <property name="basePackage" value="mapper接口包地址"></property>
8         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
9     </bean>

  basePackage:扫描包路径,中间可以用逗号或分号分隔定义多个包
  使用扫描器后,从spring容器中获取mapper的实现对象:

    //自动装配:可用于构造器和字段
    @Autowired
    private ItemsMapper itemsMapper;
    Items items = itemsMapper.selectByPrimaryKey(id);

Spring配置文件:
  

  与其他框架整合时,可将Spring的配置文件按功能分成几个几个文件,以便管理:
  在classpath下创建applicationContext-dao.xml,定义数据库链接池、SqlSessionFactory
  注意:在定义sqlSessionFactory时指定数据源dataSource和mybatis的配置文件。

  applicationContext-dao.xml:

 1     <beans xmlns="http://www.springframework.org/schema/beans"
 2         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 3         xmlns:context="http://www.springframework.org/schema/context"
 4         xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5         xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
 7             http://www.springframework.org/schema/mvc 
 8             http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
 9             http://www.springframework.org/schema/context 
10             http://www.springframework.org/schema/context/spring-context-3.2.xsd 
11             http://www.springframework.org/schema/aop 
12             http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
13             http://www.springframework.org/schema/tx 
14             http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
15         <!-- 加载配置文件 -->
16         <context:property-placeholder location="classpath:db.properties"/>
17         <!-- 数据库连接池 -->
18         <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
19                <property name="driverClassName" value="${jdbc.driver}"/>
20                 <property name="url" value="${jdbc.url}"/>
21                 <property name="username" value="${jdbc.username}"/>
22                 <property name="password" value="${jdbc.password}"/>
23                 <property name="maxActive" value="10"/>
24                 <property name="maxIdle" value="5"/>
25         </bean>    
26         <!-- mapper配置 -->
27         <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
28         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
29             <!-- 数据库连接池 -->
30             <property name="dataSource" ref="dataSource" />
31             <!-- 加载mybatis的全局配置文件 -->
32             <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
33         </bean>
34         <!-- mapper扫描器
35             mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册 
36             遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录 中
37             自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
38          -->
39         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
40             <property name="basePackage" value="mapper接口包地址"></property>
41             <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
42         </bean>
43     </beans>

  在classpath下创建applicationContext-transaction.xml,配置声明式事务管理:

  applicationContext-transaction.xml:

 1     <beans xmlns="http://www.springframework.org/schema/beans"
 2         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 3         xmlns:context="http://www.springframework.org/schema/context"
 4         xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5         xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
 7             http://www.springframework.org/schema/mvc 
 8             http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
 9             http://www.springframework.org/schema/context 
10             http://www.springframework.org/schema/context/spring-context-3.2.xsd 
11             http://www.springframework.org/schema/aop 
12             http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
13             http://www.springframework.org/schema/tx 
14             http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
15         <!-- 事务管理器 
16             对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
17         -->
18         <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
19             <!-- 数据源
20             dataSource在applicationContext-dao.xml中配置了
21              -->
22             <property name="dataSource" ref="dataSource"/>
23         </bean>
24      
25         <!-- 通知 -->
26         <tx:advice id="txAdvice" transaction-manager="transactionManager">
27             <tx:attributes>
28                 <!-- 传播行为 -->
29                 <tx:method name="save*" propagation="REQUIRED"/>
30                 <tx:method name="delete*" propagation="REQUIRED"/>
31                 <tx:method name="insert*" propagation="REQUIRED"/>
32                 <tx:method name="update*" propagation="REQUIRED"/>
33                 <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
34                 <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
35                 <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
36             </tx:attributes>
37         </tx:advice>
38         <!-- aop -->
39         <aop:config>
40             <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.luswei.ssm.service.impl.*.*(..))"/>
41         </aop:config>
42     </beans>

 

posted @ 2017-03-07 11:46  luswei  阅读(184)  评论(0编辑  收藏  举报