mybatis进阶

mybatis 进阶内容

1.1 新增操作

怎么获取自增长的值

<!-- 
将数据库插入后生成的id值,同步到java对象上
	useGeneratedKeys="是否使用由数据库生成的主键"
	 keyColumn="主键列的名称"
	 keyProperty="主键要存入哪个属性"
-->
<insert id="insert" parameterType="com.westos.entity.Student"
	useGeneratedKeys="true" keyColumn="id" keyProperty="id">
	insert into student (id, name) values (null, #{name})
</insert>

测试:

SqlSessionFactory factory = null;
    {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @Test
    public void InsertTest(){
        SqlSession sqlSession = factory.openSession();
        Student stu = new Student();
        stu.setName("wang");
        stu.setAge(23);
        System.out.println("zhiqian:"+stu.getSid());
        String sql = "com.westos.mapper.StudentMapper.insert";
        sqlSession.insert(sql,stu);
        sqlSession.commit();
        System.out.println("zhihou:"+stu.getSid());
        sqlSession.close();
    }

新插入的对象会获得数据库自增长的id值

1.2 foreach标签

删除操作:一次删除多条记录
delete from student where id in(1);
delete from student where id in(1, 2);
delete from student where id in(1, 2, 3);
// java.util.List -> 简写为 list

<!-- list (1,2,3)
	collection="要遍历的集合"
	item="临时变量名称"
	open="循环之前的符号"
	close="循环之后的符号"
	separator="每个元素的分隔符"
	delete from student where id in (1, 2, 3)
-->
<delete id="delete" parameterType="list">
  delete from student where id in
  <foreach collection="list" item="i" open="(" close=")" separator=",">
	  #{i}
  </foreach>
</delete>

1.3 if标签

多条件组合查询
按照姓名模糊查询,年龄范围查询
Map map = …
map.put(“name”, “张%”);
map.put(“minAge”, 10);
map.put(“maxAge”, 20);
可能的条件组合:
select * from student where name=#{name}
select * from student where age between #{minAge} and #{maxAge}
select * from student where name=#{name} and age between #{minAge} and #{maxAge}

//select * from student
// java.util.Map 简写为 map
<select id="selectByCondition" parameterType="map" resultType="com.westos.entity.Student">	
	select * from student
	<where>
		<if test="name != null">
		<!--where标签会为sql自动添加where并将多余的and删掉-->
		 and name=#{name}
		</if>
		<if test="minAge != null && maxAge != null">
		 and age between #{minAge} and #{maxAge}
		</if>
	</where>
</select>

动态更新
update student set name=#{}, age=#{} where id=#{}
希望实现修改哪列就在update中出现相应的set语句,而不是出现所有的列
update student set name=#{} wehre id=#{}
update student set age=#{} wehre id=#{}

<update id="update" parameterType="com.westos.entity.Student">
	update student
	<set>
		<if test="name != null">
			name = #{name},
		</if>
		<if test="age != 0">
			age = #{age},
		</if>
	</set>
	where id = #{id}
</update>

1.4 分页查询

limit 下标, 数量
方法1:物理分页(使用sql语句实现分页)
缺点:不通用,数据库不同sql语法有差异:
mysql, limit
sqlserver, top, row_number()
oracle, rownum

<!-- map
	.put("m", 下标);
	.put("n", 数量);
-->
<select id="selectByPage" parameterType="map" resultType="com.westos.entity.Student">
	select * from student limit #{m}, #{n}
</select>

方法2:逻辑分页(把所有记录都查出来,用jdbc代码实现分页)
优点:通用,sql代码都是查询所有
效率低,适合数据很少的情况

<!-- 逻辑分页 -->
<select id="selectLogical" resultType="com.westos.entity.Student">
	select * from student
</select>

测试:

// rowBounds一定要作为第三个参数
List<Student> list = sqlSession.selectList("com.westos.mapper.StudentMapper.selectLogical", null,
		new RowBounds(5, 5));
for (Student student : list) {
	System.out.println(student);
}

1.5 表和实体类不匹配

create table teacher (
id int primary key auto_increment,
first_name varchar(20),
last_name varchar(20)
);
方法1: 可以使用列别名来解决不一致问题

<select id="selectOne" parameterType="int" resultType="com.westos.entity.Teacher">
	select id,first_name firstName,last_name lastName from teacher where id = #{id}
</select>

方法2: 使用 resultMap 代替 resultType完成映射

<select id="selectOne" parameterType="int" resultMap="aaa">
	select id, first_name, last_name from teacher where id = #{id}
</select>

<!-- type="实体对象的类型"
	 id 标签用来映射主键
	 result 标签用来映射其它列
-->
<resultMap id="aaa" type="com.westos.entity.Teacher">
	<!-- column="列名" property="属性名" -->
	<id column="id" property="id"></id>
	<result column="first_name" property="firstName"></result>
	<result column="last_name" property="lastName"></result>
</resultMap>

1.6 多表连接查询的映射

商品和类别
select * from product p inner join category c on p.category_id = c.id where p.id=1;

映射需要配置两表的关系,在实体类中也要将两个对象关联。
将对应的对象作为本对象的属性。

public class Product {
    private Integer id;
    private String name;
    private BigDecimal price;

    private Category category;
    }
<!-- 把连接查询映射到两个有关系的实体类上 -->
<select id="selectById" parameterType="int" resultMap="bbb">
	select p.id, p.name, p.price, c.id cid, c.name cname
	 from product p inner join category c on p.category_id = c.id where p.id=#{id}
</select>

<!-- association 关联 -->
<resultMap id="bbb" type="com.westos.entity.Product">
	<id column="id" property="id"></id>
	<result column="name" property="name"></result>
	<result column="price" property="price"></result>
	<!-- property="关系属性名" -->
	<association property="category" javaType="com.westos.entity.Category">
		<id column="cid" property="id"></id>
		<result column="cname" property="name"></result>
	</association>
</resultMap>

测试:
在这里插入图片描述

1.7 mybatis中的缓存

  1. 一级缓存
    每个sqlsession都有一个一级缓存,只要sql语句和参数相同,只有第一次查询数据库,并且会把查询结果放入一级缓存
    之后的查询,就直接从一级缓存中获取结果

    一级缓存的作用范围,只限于一个sqlsession

  2. 二级缓存
    所有sqlSession共享的缓存

    一级缓存无需配置,而二级缓存需要配置

<!-- 开启 ProductMapper的二级缓存, 会让本mapper内的所有select利用二级缓存-->
    <cache/>

二级缓存的意义是减少与数据库的交互,从而提升程序的性能

  1. 缓存失效(自动)
    只要是执行了增,删,改的操作,缓存就应该失效,仍然从数据库查询得到最新结果

  2. 二级缓存适用场景
    当数据的查询远远多于修改时, 才有启用二级缓存的必要

1.8 #{}${} 的区别

区别1:
#{} 生成的sql语句是用?占位符的方式, 可以防止sql注入攻击
${} 生成的sql语句是直接把值进行了字符串的拼接, 有注入攻击漏洞

区别2:
${} 可以进行运算 #{} 不能运算

区别3:
#{} 在sql语句中只能替换值, 不能是表名,列名,关键字
${} 可以替换sql语句的任意部分

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值