映射文件:指导着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对象属性的值
${}: 可以获取map中的值获取pojo对象属性的值
用例子简单区分一下:
select * from tbl_employee where id = ${id} and last_name = #{lastName}
preparing:select * from tbl_employee where id = 2 and last_name = ?
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); }