mybatis 基础操作笔记
// 通过properties标签读取 properties
<properties resource="properties配置文件路径" />
// properties以键值对的形式构成
// 下文中可以通过 ${} 的形式填键名获取对应的值
<settings>
<setting name="" value="" />
</settings>
// 用于配置二级缓存(mybatis自带一级缓存)
// 配置查询延迟加载策略
// 基本没有什么作用, 所以不用, 用的时候百度
<typeAliases>
<typeAliase type="包名" alias="别名" />
// ...
<typeAliase type="com.fmg.domain.Student" alias="stu" />
</typeLaiases>
// 批量别名 namespace必须为类名, 不区分大小写
<package name="com.fmg.domain" />
<mappers>
<mapper resource="xml路径(/分割)" />
<mapper class="Dao接口(.分割)" />
// 批量注册
<package name="dao接口所在的文件夹" />
</mappers>
mybatis模糊查询
// 1. 使用 map 传递参数
// #注意hashmap 里面的键 和 sql 里面的键名一一对应
StudentDao sqlSession = SqlSessionUtil.getSession().getMapper(StudentDao.class);
// 使用map传递多个参数
Map map = new HashMap();
map.put("name", "张雅倩");
map.put("age", 25);
List<Student> sList = sqlSession.select3(map);
for (Student s: sList) {
System.out.println(s);
}
// xml参数形式
// # #{} 表示传递的就是一个值, 无法是用sql注入
// # ${} 表示传递是一个片段, 会拼接进sql
// 例如,模糊查询 实际开发中一般不用
<select id="select4" resultType="Student">
select * from tbl_student where name like '${value}'
</select>
// #{} 才是王道 切记空格
<select id="select5" resultType="Student">
select * from tbl_student where name like '%' #{name} '%'
</select>
resultMap
// id: 唯一标识符, sql语句通过id找过这个类型
<resultMap id="" type="Student">
// 这个是主键对应关系, 主键是id, 对应表中的字段也是id
<id property="id" column="id" />
// 这里的是 column 对应表中的字段, property 指的是新生成的数据字段
<result property="" column="" />
</resultMap>
动态sql
Student s = new Student();
// 这一行注释掉, 就是查询所有的, 不注释掉就是查询名字中带有 倩 字的
s.setName("倩");
List<Student> list = sqlSession.select12(s);
for (Student stu: list){
System.out.println(stu);
}
// sql 语句中的 where 和 if 的用法
<select id="select12" resultType="Student">
select * from tbl_student
<where>
<if test="name != null and name != ''">
and name like '%' #{name} '%'
</if>
</where>
</select>
本想把生活活成一首诗, 时而优雅 , 时而豪放 , 结果活成了一首歌 , 时而不靠谱 , 时而不着调