1、在用Mybatis时要先导入jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
2、学习会了配置Mybatis的核心配置文件
在Mybatis的核心配置文件中可以配置一些? 日志??、mapper.xml 、类型别名(typeAliases) 、缓存等
?
?3、用注解简化一些简单的CURD
public interface TeacherMapper{
@select("select * from teacher" wahere id = #{tid})
Teacher getTacher(@param("tid")int id);
}
?相对的就要在核心配置文件中绑定
<mappers>
<mapper class = "com.peng.dao.TeacherMapper"/>
</mappers>
4、动态 SQL
动态SQL的功能标签:if、trim (where, set)、foreach
? if标签:如果name不等于空就会拼接里面的SQL
<select>
select * from teacher
<if test = "name != null">
where name = #{name}
</if>
</select>
? where:它可以很智能的把一些多余的and去掉
<select>
select * from teacher
<where>
<if test = "id != null">
id = #{id}
</if>
<if test = "name != null">
and name = #{name}
</if>
</where>
</select>
set标签:它可以把你多加的,去除
<update>
update teacher
<set>
<if test = "password != null">
password = #{password},
</if>
<if test = "name != null">
name = #{name}
</if>
</set>
where id = #{id}
</update>
foreach标签:它可以遍历一些合集比如拼接这样的SQL:select * from 表名 where (id=? or id=?)
public interface StudentMapper {
//用动态SQL查询id=(1,2)的学生
List<Student> queryStudent(Map map);
}
<!-- 调用的方法 传入的参数 返回的参数类型 -->
<select id="queryStudent" parameterType="map" resultType="com.peng.pojo.Student">
select * from student
<where>
<!-- 要遍历的集合名 遍历后每个参数的名字 开始 分割符 结束-->
<foreach collection="ids" item="id" open=" (" separator="or" close=")">
id=#{id}
</foreach>
</where>
</select>
@Test
public void w2(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
ArrayList<Integer> list = new ArrayList<>();
HashMap hashMap = new HashMap();
list.add(1);
list.add(2);
hashMap.put("ids",list);
List<Student> students = mapper.queryStudent(hashMap);
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
?
5、缓存
缓存只要在Mapper.xml中加上<cache/>标签即可
也可以配置一些需求例如缓存策略、刷新时间、最大容量等
|