SQL写在xml中

x33g5p2x  于2021-12-28 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(289)

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

  • 在application.properties添加一句
mybatis.mapper-locations=classpath:/mybatis/mapper/*.xml

这句话用来指定xml文件的存放地。

  • 在resources目录下新建一个mybatis文件夹,在mybatis文件夹下新建mapper文件夹。
    新建一个xml文件,名字跟Dao名字一致,如TUserDao.xml,建完后的文件路径是resources/mybatis/mapper/TUserDao.xml
  • 在xml中添加sql语句,如下:
<?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">
<!-- 注意:文件名必须跟Dao类名字一致,因为是根据文件名做关联。 -->
<mapper>

    <select id="selectByName" parameterType="String" resultMap="baseResultMap">
        select * from t_user t where t.username = #{username} limit 1
    </select>

</mapper>

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

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

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

相关文章