if
choose(when,otherwise)
trim(where,set)
foreach
代码:
public interface StudentMapper {
List selectLikeName(String name);
}
不想使用所有条件时候,他们可以从多个条件中选择一个使用,相当于java 的 if ... else if ... else。
List selectChoose(@Param("id") Long id,
@Param("name") String name,@Param("clsId") Long clsId);
set 元素可以用于动态包含需要更新的列
id,name,age
update student
name =#{name},
age = #{age},
id = #{id}
void updateSet(@Param("age") Integer age,@Param("name")String name
,@Param("clsId") Long clsId,@Param("id")Long id);
foreach :用于对集合遍历。 动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)
List selectForeach(@Param("ids") List ids);
collection:传参的数组集合
item:遍历拿到的每一个元素
index:索引
open : foreach 标签内容的开始符
close : foreach 标签内容的结束符
separator:分隔符
取值取的就是 item 的元素值
注意:当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
script:要在带注解的映射器接口类中使用动态 SQL,可以使用 script 元素。
使用注解操作 mybatis
需求:查询所有的学生信息,用注解方式实现
@Select("select * from student")
List selectAll();
更新学生信息,使用 script 标签
@Update({
""
})
void updateStu(@Param("age") Integer age,@Param("name")String name
,@Param("clsId") Long clsId,@Param("id")Long id);
bind
元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。
需求:通过用户name 进行模糊查询
*官方的不用
通过这个接口SqlSession来执行命令,获取映射器实例和管理事务,SqlSessions 是由 SqlSessionFactory 实例创建的。SqlSessionFactory 对象包含创建 SqlSession 实例的各种方法。而 SqlSessionFactory 本身是由 SqlSessionFactoryBuilder 创建的,它可以从 XML、注解或 Java 配置代码来创建 SqlSessionFactory。
SqlSessionFactory build(InputStream inputStream)
SqlSessionFactory build(InputStream inputStream, String environment)
SqlSessionFactory build(InputStream inputStream, Properties properties)
SqlSessionFactory build(InputStream inputStream, String env, Properties props)
SqlSessionFactory build(Configuration config)
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);
最终会将xml 配置文件,或者 properties 配置转换成一个 Configuration ,最后一个 build 方法接受一个 Configuration 实例。Configuration 类包含了对一个 SqlSessionFactory 实例你可能关心的所有内容。
Configuration 类信息
SqlSession openSession()
SqlSession openSession(boolean autoCommit)
SqlSession openSession(Connection connection)
SqlSession openSession(TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level)
SqlSession openSession(ExecutorType execType)
SqlSession openSession(ExecutorType execType, boolean autoCommit)
SqlSession openSession(ExecutorType execType, Connection connection)
Configuration getConfiguration();
事务处理:你希望在 session 作用域中使用事务作用域,还是使用自动提交(auto-commit)?(对很多数据库和/或 JDBC 驱动来说,等同于关闭事务支持)
数据库连接:你希望 MyBatis 帮你从已配置的数据源获取连接,还是使用自己提供的连接?
语句执行:你希望 MyBatis 复用 PreparedStatement 和/或批量更新语句(包括插入语句和删除语句)吗?
默认的 openSession() 方法没有参数,它会创建具备如下特性的 SqlSession:
事务作用域将会开启(也就是不自动提交)
将由当前环境配置的 DataSource 实例中获取 Connection 对象。(mybatis-config.xml)
事务隔离级别将会使用驱动或数据源的默认设置(mysql 默认REPEATABLE_READ)
预处理语句不会被复用,也不会批量处理更新。
如果你需要开启事务自动提交
向 autoCommit
可选参数传递 true
值即可开启自动提交功能
如果你需要提供数据库隔离级别
修改这个的值TransactionIsolationLevel ,提供了枚举
如果你需要修改执行类型
修改ExecutorType值
ExecutorType.SIMPLE
:该类型的执行器没有特别的行为。它为每个语句的执行创建一个新的预处理语句。
ExecutorType.REUSE
:该类型的执行器会复用预处理语句。
ExecutorType.BATCH
:该类型的执行器会批量执行所有更新语句,如果 SELECT 在多个更新中间执行,将在必要时将多条更新语句分隔开来,以方便理解。
语句执行方法:这些方法被用来执行定义在 SQL 映射 XML 文件中的 SELECT、INSERT、UPDATE 和 DELETE 语句。
T selectOne(String statement, Object parameter)
List selectList(String statement, Object parameter)
Cursor selectCursor(String statement, Object parameter)
Map selectMap(String statement, Object parameter, String mapKey)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
RowBounds(可用于分页需求)
int offset = 100;
int limit = 25;
RowBounds rowBounds = new RowBounds(offset, limit);
立即批量更新方法(如果不调用这个方法,批处理不执行,只是缓存而已)
List flushStatements()
事务控制方法
void commit()
void commit(boolean force)
void rollback()
void rollback(boolean force)
本地缓存:Mybatis 使用到了两种缓存:
本地缓存(local cache):每当一个新 session 被创建,MyBatis 就会创建一个与之相关联的本地缓存
二级缓存(second level cache)
清空本地缓存(一般不去动)
void clearCache()
确保 SqlSession 被关闭:如果没有使用新特性的方式,一定要finally手动关闭
void close()
T getMapper(Class type)
public interface AuthorMapper {
// (Author) selectOne("selectAuthor",5);
Author selectAuthor(int id);
// (List) selectList(“selectAuthors”)
List selectAuthors();
// (Map) selectMap("selectAuthors", "id")
@MapKey("id")
Map selectAuthors();
// insert("insertAuthor", author)
int insertAuthor(Author author);
// updateAuthor("updateAuthor", author)
int updateAuthor(Author author);
// delete("deleteAuthor",5)
int deleteAuthor(int id);
}
插入语句
@Insert("insert into table3 (id, name) values(#{nameId}, #{name})")
int insertTable3(Name name);
查询语句
@Results(id = "userResult", value = {
@Result(property = "id", column = "uid", id = true),
@Result(property = "firstName", column = "first_name"),
@Result(property = "lastName", column = "last_name")
})
@Select("select * from users where id = #{id}")
User getUserById(Integer id);
MyBatis 分页插件 PageHelper:是一款非常不错,并且企业用得很多的mybatis 分页插件
导入 maven 依赖 pom
com.github.pagehelper
pagehelper
5.3.0
在 spring 中配置
params=value1
pageNum : 当前页码,pageSize : 每页显示的数量,list : 分页后的集合数据,total : 总记录数,
pages : 总页数,prePage : 上一页,nextPage: 下一页。
//①:开启分页功能,参数1是当前页码,参数是每页显示的条数
PageHelper.startPage(1, 2);
//②:开始执行结果,返回list
List list = mapper.selectAll();
Page page = (Page) list;
PageInfo info = new PageInfo<>(list);
System.out.println(list);
page 里面包含的属性
private int pageNum;
private int pageSize;
private long total;
private int pages;
insert into student values(null,#{name},#{age},#{classId})
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH,true)) {
StudentMapper mapper = session.getMapper(StudentMapper.class);
Student student = new Student();
mapper.insert(student);
Student student1 = new Student();
mapper.insert(student1);
List batchResults = session.flushStatements();
} catch (Exception e) {
e.printStackTrace();
}
insert into student (name,age) values
(#{stu.name},#{stu.age})
int batchInsert(List list);
$(ids)
@Delete("delete from student where id in(${ids})")
int deleteBatch(String ids);
foreach
delete from student
#{id}
如果是给某一堆id 修改相同属性值,可以使用foreach