---
title: "Mybatis系列之实战篇（下）"
author: "禹爸爸"
date: "2015-10-19T20:30:10Z"
tags: []
categories: ["编程语言"]
slug: "mybatis"
draft: false
lastmod: "2015-10-19T20:28:58Z"
id: 2250009
url: "https://cmao.iteye.com/blog/2250009"
---

# Mybatis系列之实战篇（下）

## 实战总结

- 将Mybatis和Spring配置文件独立开

```
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource" />
	<!-- 自动扫描mapping.xml文件 -->
	<property name="mapperLocations" value="classpath:com/emerson/etao/mapping/**/*.xml"></property>
	<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
```

- 数据库连接信息单独存放，方便在多个配置文件中引用
- 使用Mybatis接口式编程，只需要定义接口，不需要自己动手编写实现类
- 在编写映射文件时，根元素名称空间一定要使用定义的接口的全限定名
- 映射文件中的元素的id值，要和接口中定义的方法名称一一对应
- 对数据的增、删、改、查操作，统一方法名称，不仅可以提取出超类，也可以统一映射文件中元素的命名规则，便于理解和维护

```
<select id="getById" parameterType="int" resultType=""></select>

<select id="getAll" resultType=""></select>

<insert id="insert" parameterType="" useGeneratedKeys="true" keyProperty=""></insert>

<update id="update" parameterType=""></update>

<delete id="delete" parameterType="int"></delete>
```

- 在映射文件的select元素中，不要使用select \*，尽可能将每个字段写出来，如果有些字段会出现在多个select元素中，可以将其提取出来

```
<sql id="selectColumns"></sql>

<sql id="insertColumns"></sql>

<select id="getById" parameterType="int" resultType="">
        SELECT
        <include refid="selectColumns"></include>
        FROM TABLENAME WHERE KEY_FIELD = #{id}
</select>
```

- 能自动映射的，就不要动手编写resultMap
- 在定义resultMap时，尽量不要使用嵌套查询，这样会带来“N+1”问题；使用嵌套结果代替嵌套查询
- 映射文件中定义的resultMap，尽可能的复用，不要在多个映射文件中定义相同的resultMap，这样会给日后的调试和维护带来不必要的麻烦
- 映射文件中每增加一个元素，都要对代码进行测元测试，发现问题及时修复；
- 避免一次编写过多尤其是复杂的映射语句，因为这样一旦出现问题，会消耗很多时间来查找问题原因，而这些问题往往是由很低级的错误造成的

以上是个人拙见，供参考。