映射文件:指导着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. app耗电优化之四 使用AlarmManager对任务进行合理安排

    AlarmManager 是用来设定定时任务.即用来设定那个任务在什么时候开始执行.为什么和省电有关系?这个需要和AlarmManager的使用先说起.AlarmManager 实际上只起到一个定时发 ...

  2. 函数响应式编程及ReactiveObjC学习笔记 (四)

    今天我们继续看其他的类别 UIImagePickerController+RACSignalSupport.h #import <UIKit/UIKit.h> @class RACDele ...

  3. Verilog HDL常用综合语法

    前面已经记录了一些组成Verilog的基本组成,可以用这些基本组成来构成表达式.这一节,就来记录一下把这些表达式构成一个文件的各种行为描述语句. ①这里用Verilog基本要素进行的行为描述主要是针对 ...

  4. JStorm与Storm源码分析(五)--SpoutOutputCollector与代理模式

    本文主要是解析SpoutOutputCollector源码,顺便分析该类中所涉及的设计模式–代理模式. 首先介绍一下Spout输出收集器接口–ISpoutOutputCollector,该接口主要声明 ...

  5. phpMyAdmin安装部署

    phpMyAdmin 是一个用PHP编写的软件工具,可以通过web方式控制和操作MySQL数据库.通过phpMyAdmin 可以完全对数据库进行操作,例如建立.复制和删除数据等等.如果使用合适的工具, ...

  6. 花了一年时间开发的弯管机YBC编程软件

    弯管技术广泛应用于锅炉及压力容器,空调制造,汽车,航空航天等多种行业.管型的形状复杂多变弯管工艺人员通常依据图纸输入关键点的坐标(XYZ坐标),然后生成可以由弯管机设备直接直接完成的加工指令YBC数据 ...

  7. mybatis 详解(一)------JDBC

    1.什么是MyBatis? MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且 ...

  8. python中list总结

    转自python中list总结 一.list可以看做是一个数据结构,也是一个class, 用help(list)可以看见其方法,元素的增删改查都有各种现成的方法, 二.list操作包含以下函数:1.c ...

  9. ABP+AdminLTE+Bootstrap Table权限管理系统第十一节--bootstrap table之用户管理列表

    这张开始bootstrap table,引入项目有两种方法,一种是直接去官网下载 地址:http://bootstrap-table.wenzhixin.net.cn/ 另一种是Nuget引入. 然后 ...

  10. 一个普通的 Zepto 源码分析(二) - ajax 模块

    一个普通的 Zepto 源码分析(二) - ajax 模块 普通的路人,普通地瞧.分析时使用的是目前最新 1.2.0 版本. Zepto 可以由许多模块组成,默认包含的模块有 zepto 核心模块,以 ...