赞
踩
之前的SQL语句是基于注解
以后开发中一般是一个接口对应一个映射文件
书写映射文件
基本结构 框架
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="org.example.mybatis.mapper.UserMapper">
-
- </mapper>
完整形式
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <!--复制引用-->
- <mapper namespace="org.example.mybatis.mapper.UserMapper">
-
- <!--查询操作-->
- <!--result 表示 单条记录封装类型的全类名-->
- <select id="list" resultType="org.example.mybatis.pojo.User">
- select * from emp
- where name like concat('%',#{name},'%')
- and gender = #{gender}
- and entrydate between #{begin} and #{end}
- order by update_time desc
- </select>
-
- </mapper>

Invalid bound statement (not found)
要保持resources目录的com.xxx.mapper和java目录下的com.xxx.mapper名称完全一致
血的教训是改了一天的bug发现mybatis拼写成了mabatis
- @Test
- public void testList() {
- List<User> userList = userMapper.list("张", (short) 1,
- LocalDate.of(2010, 1, 1),
- LocalDate.of(2020, 1, 1));
- System.out.println(userList);
- }
- package org.example.mybatis.mapper;
-
- import org.apache.ibatis.annotations.*;
- import org.example.mybatis.pojo.User;
-
- import java.time.LocalDate;
- import java.util.List;
-
- @Mapper//表示当前是Mybatis的一个接口 此时程序运行时框架会自动生成实现类对象(代理对象) 并交给spring的ioc容器
- public interface UserMapper {
-
- //根据xml配置文件查询
- public List<User> list(String name, Short gender ,LocalDate begin ,LocalDate end);
-
- }
通过映射 能通过写在mapper接口里的list方法
找到SQL语句
使用注解的方式 就不会出现这个问题
使用xml配置文件要分开写
映射上去
根据接口中方法名找到对应的接口方法
如果随意配置 就找不到了 这样调用mapper接口里的list方法就找不到了
插件
点击小鸟可以直接跳转
这样就能关联
这样我们就学习了基于注解的方式实现SQL 和 基于XML文件的方式实现SQL
使用注解映射简单的语句会使代码更加简洁
但是对于稍微复杂一点的语句 Java注解力不从心
因此 如果想实现稍微复杂一点的操作 最好用XML语句来映射语句
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。