1mybatis事务
mybatis事务的管理也是通过setAutoCommit() 进行控制,
默认为手动提交
简单的事务设置:
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
在手动提交方式遇到增删改时,需要调用session.commit();
自动提交设置
SqlSession sqlSession = sqlSessionFactory.openSession(true);
2Mybatis 的动态 SQL 语句
场景
在实际应用开发过程中,我们往往需要写复杂的 SQL 语句,需要拼接,而拼接SQL语句又稍微不注意,由于引号,空格等缺失可能都会导致错误。
Mybatis提供了动态SQL,也就是可以根据用户提供的参数,动态决定查询语句依赖的查询条件或SQL语句的内容。
动态sql语句
1.IStudentDao接口中增加
List<Student> findStudentByCondition(Student student);
2.在IStudentDao.xml增加
<select id="findStudentByCondition" resultType="student" parameterType="student">
select * from student_tb where 1=1
<if test="name != null and name !=''">
and name like #{name}
</if>
<if test="sex != null and sex != ''">
and sex like #{sex}
</if>
</select>
当if条件符合要求是才会拼接sql语句,注意where 1=1 是为了解决两个条件都符合时sql的where条件
3.测试
private static void findStudentByCondition(IStudentDao studentDao) {
Student student = new Student();
student.setName("%ang%");
student.setSex("%M%");
List<Student> studentList = studentDao.findStudentByCondition(student);
for (Student studentTemp:studentList){
System.out.println(studentTemp);
}
}
动态sql语句
可以替代sql语句中的where
沿用上一个例子,将配置文件改为一下,避免where 1=1
<select id="findStudentByCondition" resultType="student" parameterType="student">
select * from student_tb
<where>
<if test="name != null">
and name like #{name}
</if>
<if test="sex != null">
and sex like #{sex}
</if>
</where>
动态语句
标签是为解决mybatis接受集合参数设置的。适用场景如下
select * from student where id in(43,44,58,59);
1.IStudentDao接口中增加
List<Student> findStudentByIds(QuestData questData);
将请求的参数集合封装为对象
public class QuestData {
List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
2.在IStudentDao.xml增加
<select id="findStudentByIds" resultType="student" parameterType="QuestData">
select * from student_tb
<where>
<if test="ids!=null and ids.size()>0">
<foreach collection="ids" open="and id in(" close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
- collection:为接受ids的变量名
- open:表示以什么字段开始
- close:表示以什么字段结束
- item:为遍历集合中的元素
- separator:为切分集合到的标记
动态语句
在xml配置我们可以通过完成语句的声明,通过 标签进行应用拼接
<sql id="findAllStudentsql">
select * from student_tb
</sql>
<select id="findAllStudent" resultType="com.wgz.entity.Student">
<include refid="findAllStudentsql"></include> where id >40
</select>