6.单表的CRUD操作
1.插入后用新id初始化被插入对象
1 <insert id="insertStudentCatchId"> 2 insert into student (age,name,score) values (#{age},#{name},#{score}); <!-- #{}中写入的是Student类的属性名 --> 3 4 <!-- 子标签 selectKey 用于获取新插入记录的主键值 --> 5 <!-- 使用新插入记录的主键值初始化被插入的对象 --> 6 <selectKey resultType="int" keyProperty="id" order="AFTER"> 7 select @@identity 8 </selectKey> 9 </insert>
2.删除数据
1 <delete id="delecteStudent"> 2 delete from student where id = #{id} <!-- 这里的id就是是直接传过来的一个整数,不是通过对象来进行传递的,所以#{id} 充当的是 占位符,{} 可以写任意字符 --> 3 </delete>
3.修改数据
1 <update id="updateStudent"> 2 update student set name = #{name},age = #{age},score = #{score} where id = #{id} 3 </update>
4.查询所有对象-返回List
1 <!-- 这里需要使用resultType指定结果类型,不然查询出来了,都不知道构成什么对象 --> 2 <select id="selectAllStudent" resultType="com.mybatis.model.Student"> <!-- 因为这里没有设置别名,所以需要加上包全名 --> 3 select * from student 4 </select>
1 sqlSession = SqlSessionUtil.getSqlSession(); 2 students = sqlSession.selectList("selectAllStudent");
resultType 属性并非指查询结果集最后的类型,而是每查出 DB 中的一条记录,将该记录封装成为指定对象的类型
通过 selectList()方法完成查询操作,该方法会将查询出来的已经封装好的对象,放到一个List中返回
5.查询所有对象-返回Map
和返回List类似,区别是最后是要放到Map容器中的,所以需要指定将对象 put 进 map时的 key
1 sqlSession = SqlSessionUtil.getSqlSession(); 2 //查询出的结果是一个Map,这个Map的key是 指定对象的值 (如:xzk)根据这个key 可以查询对应的value,value就是student对象 3 studentsMap = sqlSession.selectMap("selectStudentMap", "name");
6.查询单个对象
使用SqlSession的selectOne()方法。其会将查询的结果记录封装为一个指定类型的对象
1 <select id="selectStudentById" resultType="com.mybatis.model.Student"> 2 select * from student where id = #{id} <!-- 这里 #{id} 同样是占位符--> 3 </select>
1 sqlSession = SqlSessionUtil.getSqlSession(); 2 student = sqlSession.selectOne("selectStudentById", id);
7.根据Map进行查询
mapper中SQL语句的动态参数也可以是Map的key
8.模糊查询
1 <select id="selectStudentsByName" resultType="com.mybatis.model.Student"> 2 select * from student where name like '%' #{name} '%' //1 1和2是等价的 3 <!-- select * from student where name like concat ('%' #{xx} '%') --> //2 4 <!-- select * from student where name like '%${value}%' --> 5 </select>
进行模糊查询时,需要进行字符串的拼接。SQL中字符串的拼接使用的是 concat() 函数,注意不能使用Java中的字符串连接符
第一条和第二条语句都是等价的,都是以动态参数(name=?)的形式出现在SQL语句中
还可以使用第三条语句的方式,只是需要注意,${ } 中只能使用 value,不能使用其它
而且,这种方式是纯粹的字符串拼接,直接将参数拼接到了SQL语句中。这种方式可能会发生SQL注入
$ 和 # 的区别
A、理论区别
$ 与 # 的 区别是很大的。#为占位符,而$为字符串拼接符
字符串拼接是将参数值以硬编码的方式直接拼接到了SQL语句中。字符串拼接会引发两个问题:
SQL注入问题与没有预编译所导致的执行效率底下的问题
占位符的引入,解决以上两个问题
B、执行区别
上面已经提到,一个是为SQL动态地进行赋值,一个是直接定死在SQL语句中,类似statement 和 prepareStatement的区别
C、应用场景
一般情况下,动态参数的值是由用户输入的,则不能使用拼接符$,因为有可能会出现SQL 注入;
若动态参数的值是由系统计算生成的,则可以使用拼接符$。但这样虽然不存在SQL 注入的风险,但仍存在执行效率问题。