映射文件:指导着MyBatis如何进行数据库增删改查, 有着非常重要的意义;
 
- cache   命名空间的二级缓存配置
- cache-ref   其他命名空间缓存配置的引用。
- resultMap    自定义结果集映射
- parameterMap    已废弃!老式风格的参数映射
- sql    抽取可重用语句块
- insert    映射插入语句
- update    映射更新语句
- delete    映射删除语句
- select    映射查询语句
 
1.先看增删改查标签

public interface EmployeeMapper {
/*
* 增删改查方法
* */
public Employee getEmployeeById(Integer id);
public void insertEmp(Employee employee);
}
在其对应的sql映射文件中:      
useGeneratedKeys="true":默认使用主键自增的主键
keyProperty="id":将主键赋值给 id 属性
这样就可以在insert函数中获取新添加的用户的 id主键,否则获取不到

<select id="getEmployeeById" resultType="employee" databaseId="mysql">
select * from student where id = #{id}
</select> <insert id="insertEmp" parameterType="com.neuedu.entity.Employee" useGeneratedKeys="true" keyProperty="id">
insert into student(name,password,email) values(#{name},#{password},#{email})
</insert>

编写测试单元:

private EmployeeMapper mapper = null;
private SqlSession session = null;
@Before
public void testBefore(){
//1.获取sqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
//2.利用sqlSessionFactory创建一个session对象,表示和数据库的一次会话
session = sqlSessionFactory.openSession();
//3.用session对象获取mapper接口的代理对象
//因为sql映射文件给相应的接口创建了一个代理对象,所以mapper接口类不需要实现类
mapper = session.getMapper(EmployeeMapper.class);
} @Test
public void testSelect(){
mapper = session.getMapper(EmployeeMapper.class);
//4.通过mapper接口的代理对象就可以对数据库进行增删改查操作
Employee employee = mapper.getEmployeeById(4);
System.out.println(employee);
}
@Test
public void testInsert(){
Employee emp = new Employee("zhangsan", "1234567", "zhangsan@q.com");
mapper.insertEmp(emp);
int id = emp.getId();
System.out.println(id);
}
@After
public void testAfter(){
//增删改需要提交事务
session.commit();
session.close();
}
//@Before、@After自动在@Test之前和之后运行
//查询不需要提交事务,增删改都需要提交事务

2.获取自增主键值【当向数据库中插入一条数据的时候,默认是拿不到主键的值的, 需要设置如下两个属性才可以拿到主键值!】

<!--设置userGeneratedKeys属性值为true:使用自动增长的主键。使用keyProperty设置把主键值设置给哪一个属性-->
<insert id="addEmp" parameterType="com.neuedu.mybatis.bean.Employee" useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
insert into tbl_employee(last_name,email,gender) values(#{lastName},#{gender},#{email})
</insert>
3.SQL节点:
   1).可以用于存储被重用的SQL片段
   2).在sql映射文件中,具体使用方式如下:

<sql id="npe">
name,password,email
</sql>
<insert id="insertEmp" parameterType="com.neuedu.entity.Employee" useGeneratedKeys="true" keyProperty="id">
insert into student(<include refid="npe"></include>) values(#{name},#{password},#{email})
</insert>

参数处理
 
- 单个参数:Mybatis 不会特殊处理
  #{参数名}: 取出参数值,参数名任意写
- 多个参数:Mybatis会做特殊处理,多个参数会被封装成一个map 

  key:param1...paramN,或者参数的索引也可以(0,1,2,3.....)
       value:传入的参数值
       #{ }就是从map中获取指定的key的值
       命名参数:明确指定封装参数时map的key:@param("id")
                 多个参数会被封装成一个map,
                   key:使用@Param注解指定的值
                   value:参数值
                   #{指定的key}取出对应的参数值

public void updateEmp(@Param("id")Integer id,
@Param("name")String name,
@Param("password")String password,
@Param("email")String email);
<update id="updateEmp">
update student set name=#{name},password=#{password},email=#{email} where id=#{id}
</update>

- POJO参数:如果多个参数正好是我们业务逻辑的数据模型,我们就可以直接传入POJO

  #{属性名}:取出传入的POJO的属性值

public void insertEmp(Employee employee);
<sql id="npe">
name,password,email
</sql>
<insert id="insertEmp" parameterType="com.neuedu.entity.Employee" useGeneratedKeys="true" keyProperty="id">
insert into student(<include refid="npe"></include>) values(#{name},#{password},#{email})
</insert>
@Test
public void testReturnVal(){
Employee employee = mapper.getEmployeeById(30);
System.out.println(employee);
}

- Map:如果多个参数不是业务模型中的数据,没有对应的pojo,不经常使用,为了方便,我们也可以传入Map

  #{key}:根据 key 取出map中对应的值

public void updateName(Map<String, Object> map);
<update id="updateName">
update student set name=#{name} where id=#{id}
</update>
@Test
public void testMap(){
Map<String, Object> map = new HashMap<>();
map.put("id", 33);
map.put("name", "刘德华");
mapper.updateName(map);
}
#关于参数的问题:
    ①.使用#{}来传递参数
    ②.若目标方法的参数类型为对象类型,则调用其对应的getter方法,如getEmail()
    ③.若目标方法的参数类型为Map类型,则调用其get(key)
    ④.若参数是单个的,或者列表,需要使用@param注解来进行标记
    ⑤.注意:若只有一个参数,则可以省略@param注解
                   若有多个参数,必须要写@param注解
  
 

参数值的获取
#{}:可以获取map中的值或者pojo对象属性的值
${}: 可以获取map中的值获取pojo对象属性的值
 
用例子简单区分一下:
select * from tbl_employee where id = ${id} and last_name = #{lastName}
preparing:select * from tbl_employee where id = 2 and last_name = ?
也就是说:对于${} 在日志中可以看到你输入的值,不安全;
     对于#{} 在日志中是?,所以相对安全
 
具体区别:
#{}:是以预编译的形式,将参数设置到sql语句中,相当于PreparedStatement;防止sql注入

<update id="updateEmp">
update student set name=#{name},password=#{password},email=#{email} where id=#{id}
</update>

${}:取出的值直接拼装在sql语句中,会有安全问题

<update id="updateEmp">
update student set name='${name}',password='${password}',email='${email}' where id='${id}'
</update>

大多情况下,我们取参数的值都应该去使用#{}
但是原生JDBC不支持占位符的地方我们就可以使用${}进行取值
比如获取表名、分表、排序;按照年份分表拆分
- select * from ${year}_salary where xxx;[表名不支持预编译]
- select * from tbl_employee order by ${f_name} ${order} :排序是不支持预编译的!
 
 

select 元素
select元素来定义查询操作。
  Id:唯一标识符。
             用来引用这条语句,需要和接口的方法名一致
  parameterType:参数类型。
             可以不传,MyBatis会根据TypeHandler自动推断
  resultType:返回值类型。
             别名或者全类名,如果返回的是集合,定义集合中元素的类型。不能和resultMap同时使用 
 
1.返回类型为一个List
public List<Employee> getEmps();
<select id="getEmps" resultType="com.neuedu.entity.Employee">
select * from student
</select>
@Test
public void testReturnList(){
List<Employee> emps = mapper.getEmps();
for (Employee employee : emps) {
System.out.println(employee);
}
}

2.返回记录为一个Map

只能查询单条数据,如果多条的话,多个key 值,找不到

public Map<String, Object> getEmpInfoById(Integer id);

resultType 是 Map 的全类名

<select id="getEmpInfoById" ="java.util.Map">
select * from student where id = #{id}
</select>

key:列名;value:值

@Test
public void testReturnMap(){
Map<String, Object> emp = mapper.getEmpInfoById(30);
Set<Entry<String,Object>> entrySet = emp.entrySet(); for (Entry<String, Object> entry : entrySet) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}

数据库列名与实体类的属性名不对应的情况下有几种处理方式:
1.sql 语句 用 as 换名
2.下划线转换成驼峰式命名
   在全局配置文件中

<settings>
<!-- setting标签负责每一个属性的设置 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

3.利用ResultMap:

public Employee getEmpInfoById(Integer id);
<resultMap type="com.neuedu.entity.Employee" id="getEmployByIdMap">
<!-- 主键映射可以用 id 字段,mybatis在底层会做优化,主键有索引,加快查询速度 -->
<id column="id" property="id"/>
<!-- 普通列的映射使用result -->
<result column="name" property="name"/>
<result column="password" property="password"/>//相同的也可以不写,但因为规范建议写
<result column="email" property="email"/>
</resultMap>
<select id="getEmpInfoById" resultMap="getEmployByIdMap">
select * from student where id = #{id}
</select>
@Test
public void testReturnMap(){
Employee emp = mapper.getEmpInfoById(30);
System.out.println(emp);
}

Mybatis --- 映射文件、参数处理、参数值的获取、select元素的更多相关文章

  1. mybatis映射文件参数处理 #{}取值与${}取值的区别

    #{}:是以预编译的映射,将参数设置到sql语句中,和jdbc的preraredStatement一样,使用占位符,防止sql注入. ${}:取出的值会直接拼装在sql中,会有安全问题. 大多数情况下 ...

  2. MyBatis映射文件中用#和$传递参数的特点

    在MyBatis映射文件中用#和$传递参数的特点, #是以占位符的形式来传递对应变量的参数值的,框架会对传入的参数做预编译的动作, 用$时会将传入的变量的参数值原样的传递过去,并且用$传递传递参数的时 ...

  3. Mybatis映射文件中#取值时指定参数相关规则

    Mybatis映射文件中#取值时指定参数相关规则 在#{}中,除了需要的数值外,还可以规定参数的一些其他规则. 例如:javaType,jdbcType,mode(存储过程),numericScale ...

  4. mybatis映射文件#与$的使用,及参数传入规则

    mybaits映射文件中使用#与$场景: <select id="getProviders" resultType="com.lazy.bill.pojo.Prov ...

  5. Mybatis映射文件的自动映射与手动映射问题

    Mapper XML 文件 MyBatis 的真正强大在于它的映射语句,也是它的魔力所在.由于它的异常强大,映射器的 XML 文件就显得相对简单.如果拿它跟具有相同功能的 JDBC 代码进行对比,你会 ...

  6. SSM实战——秒杀系统之DAO层实体定义、接口设计、mybatis映射文件编写、整合Spring与Mybatis

    一:DAO实体编码 1:首先,在src目录下,新建org.myseckill.entity包,用于存放实体类: 2:实体类设计 根据前面创建的数据库表以及映射关系,创建实体类. 表一:秒杀商品表 对应 ...

  7. MyBatis 映射文件详解

    1. MyBatis 映射文件之<select>标签 <select>用来定义查询操作; "id": 唯一标识符,需要和接口中的方法名一致; paramet ...

  8. MyBatis映射文件 相关操作

    一.MyBatis映射文件 1.简介 MyBatis 的真正强大在于它的映射语句,也是它的魔力所在.由于它的异常强大,映射器的 XML 文件就显得相对简单.如果拿它跟具有相同功能的 JDBC 代码进行 ...

  9. MyBatis 映射文件详解(六)

    MyBatis 配置文件类型 MyBatis配置文件有两种类型,如下: 全局配置文件(如 mybatis-config.xml) Mapper XML 映射文件(如 UserMapper.xml) 上 ...

  10. MyBatis 映射文件

    Mybatis映射文件简介 1) MyBatis 的真正强大在于它的映射语句.由于它的异常强大,映射器的 XML 文件就显得相对简单.如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉 ...

随机推荐

  1. java服务端和用户端

    1.server Logintherad: package com.zdsofe.server; import java.io.InputStream; import java.io.OutputSt ...

  2. git分支管理之Feature分支

    软件开发中,总有无穷无尽的新的功能要不断添加进来. 添加一个新功能时,你肯定不希望因为一些实验性质的代码,把主分支搞乱了,所以,每添加一个新功能,最好新建一个feature分支,在上面开发,完成后,合 ...

  3. laravel框架cookie应用到中间件的理解

    昨天博主接到一个委托的需求,大数据同事想要在请求日志抓取数据,希望在我的每个页面进行cookie的种植,方便他们进行定位分析,我思考了一下,简单呀,首先考虑的是通过中间件进行cookie种植,但是随后 ...

  4. spring学习之spring 插件 for eclipse

    1) 在公司一直使用固定的eclipse IDE版本3.3 确实太out了. eclipse官方网址:http://download.eclipse.org  奇怪的是eclipse 发布的版本顺序是 ...

  5. NYOJ 108 士兵杀敌1(树状数组)

    首先,要先讲讲树状数组: 树状数组(Binary Indexed Tree(BIT), Fenwick Tree)是一个查询和修改复杂度都为log(n)的数据结构.主要用于查询任意两位之间的所有元素之 ...

  6. CharMatch(括号匹配)

    用自己定义的链栈实现括号匹配 #include"LinkStack.h" bool Match(char *s) { LinkStack<char> tmpS; cha ...

  7. 一步一步学MySQL-日志文件

    错误日志 错误日志不用多说,记录了mysql运行过程中的错误信息,当出现问题时,我们可以通过错误日志查找线索. 慢查询日志 可以通过参数long_query_time来设置时间,当sql语句执行超过指 ...

  8. 28.Implement strStr()【leetcod】

    Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle ...

  9. 手脱ASPack

    ESP定律到达OEP,重新分析代码块 在菜单栏中找到OllyDump插件,该插件的窗口的弹了出来,有一些选项可供我们修改,我们可以对Base of Code进行修改,这里Base of Code = ...

  10. js实现轮播图动画

    在网页浏览中,可以看到轮播图是无处不在的,这是一个前端工程最基本的技巧.首先看看几个网页的呈现的效果. QQ音乐: 网易云音乐: 天猫: 接下来将从简到难总结几种实现轮播图的方法. 1.样式一:鼠标滑 ...