# 自定义SQL

# 方式1

直接写在Mapper.java中

public interface TUserMapper extends CrudMapper<TUser, Integer> {

    // 自定义sql,官方自带,不需要写xml
    /**
     * 修改用户名
     * @param id
     * @param username
     * @return 返回影响行数
     */
    @Update("update t_user set username = #{username} where id = #{id}")
    int updateById(@Param("id") int id, @Param("username") String username);
 
}

简单SQL可采用这种形式。

# 方式2

fastmybatis提供的Mapper已经满足大部分的操作需求,但是有些复杂的sql语句还是需要写在xml文件中。fastmybatis同样支持将sql语句写在xml中,具体配置如下:

  • 在application.properties添加一句,指定xml文件存放路径
mybatis.mapper-locations=classpath:/mybatis/mapper/*.xml
  • 在resources/mybatis/mapper目录下新建一个xml文件TUserMapper.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mayapp.mapper.TUserMapper">
	
	<select id="selectByName" parameterType="String" resultMap="baseResultMap">
		select * from t_user t where t.username = #{username} limit 1
	</select>
	
</mapper>

这个xml文件跟其它的mybatis配置文件一样,baseResultMap没有看到定义,但是确实存在,因为这个是fastmybatis提供的一个内置resultMap。

  • 在TUseroMapper.java中添加:
TUser selectByName(@Param("username")String username);
  • 编写单元测试用例
@Test
public void testSelectByName() {
    TUser user = dao.selectByName("张三");

    System.out.println(user.getUsername());
}
    

# 多文件同一个namespace

在以往的开发过程中,一个Mapper对应一个xml文件(namespace)。如果多人同时在一个xml中写SQL的话会造成各种冲突(虽然能够最终被解决)。

fastmybatis打破这种常规,允许不同的xml文件定义相同的namespace,程序启动时会自动把他们的内容合并到同一个文件当中去。

  • 张三的UserMapper_zs.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mayapp.mapper.TUserMapper">
	
	<select id="selectByName" parameterType="String" resultMap="baseResultMap">
		select * from t_user t where t.username = #{username} limit 1
	</select>
	
</mapper>
  • 李四的UserMapper_ls.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mayapp.mapper.TUserMapper">
	
	<select id="updateUser" parameterType="String" resultMap="baseResultMap">
		update t_user set username = #{username} where id=#{id}
	</select>
	
</mapper>

最终会合并成

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mayapp.mapper.TUserMapper">
    <!-- 张三部分 -->
    <select id="selectByName" parameterType="String" resultMap="baseResultMap">
		select * from t_user t where t.username = #{username} limit 1
	</select>
	
	<!-- 李四部分 -->
	<select id="updateUser" parameterType="String" resultMap="baseResultMap">
		update t_user set username = #{username} where id=#{id}
	</select>
	
</mapper>

这样也体现了开闭原则,即新增一个功能只需要新增一个文件就行,不需要修改原来的文件。

如果SQL写多了还可以把它们进行分类,放到不同的xml中,便于管理。

**注:**合并动作是在启动时进行的,并不会生成一个真实的文件。