- 封装工具类
public class SqlSessionUtil {
private static SqlSessionFactory factory;
//MyBatis作者认为,在应用程序运行过程中,SessionFactory对象有且只应该有一个
static {
try {
InputStream in = Resources.getResourceAsStream("mybatis.xml");
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession openSession(boolean autoCommit){
return factory.openSession(autoCommit);
}
}
- 测试语句
update dept set dname='人事部门',loc='地点' where deptno=50
- 执行sqlsession
@Test
public void test()throws Exception{
SqlSession sqlSession = SqlSessionUtil.openSession(true);
int result = sqlSession.update("dept.update");
sqlSession.close();
System.out.println("更新了"+result+"部门");
}
二、mybatis框架服务---查询结果映射服务
-
前提:使用jdbc技术推送查询时,会得到一个临时表的引用(resultset)
此时需要手动将临时表中的数据行转换成Java中相关类型对象
List deptList = new ArrayList();
resultset rs = ps.executeQuery(select * from Dept)
while(rs.next()){
int deptNo = rs.getInt("deptNo");
.........
deptList.add(dept);
}
随着表中字段个数的增加,rs.getXXX方法调用次数也会逐渐增加,最终会影响开发效率,增加开发难度。
-
查询结果映射服务:MyBatis会根据开发人员提供的类型,自动的讲临时表中的数据行转变为对应的Java对象,避免开发人员手动进行转换。
-
如何通知MyBatis,当前临时表数据行需要转换的类型
-
resultType属性:
-
resultMap属性:
-
@Test
public void test1()throws Exception{
SqlSession sqlSession = SqlSessionUtil.openSession(true);
int deptNo =sqlSession.selectOne("dept.deptCount");//只有确信查询语句返回的临时表只有一行数据时,才可以使用selectOne
sqlSession.close();
System.out.println("部门的个数是 "+deptNo);
}
- resultType:
-
resultType可以指定Java中的类型,也可以指定自定义的实体类
-
如果resultType指定的是【自定义的实体类】需要遵守:
-
要求实体类属性名应该与临时表中字段名相同,但是可以忽略英文大小写
-
-
- resultMap:
-
MyBatis允许开发人员自行设置临时表中字段与转换类型之间映射关系。此时可以通过resultMap来设置自定义映射关系。
-
@Test
public void test1()throws Exception{
SqlSession sqlSession = SqlSessionUtil.openSession(true);
Dept dept =sqlSession.selectOne("dept.findByDeptNo");
sqlSession.close();
System.out.println(dept.toString());
}
三、占位符自动赋值服务
-
前提:jdbc规范中提供了预编译的SQL命令格式,降低动态SQL书写难度,同时也可以防止SQL注入攻击
insert into dept values (?,?,?)。
但是在jdbc规范中,需要开发人员手动完成占位符的赋值操作,如下:
ps.setInt(2,10)
ps.setString(2,"BeiJing")
-
parameterType:占位符参数类型,用于帮助MyBatis将参数赋值到指定的占位符中
delete from dept where deptNo=#{deptNo} insert into dept values(#{deptNo},#{dname},#{loc})
@Test
public void test1()throws Exception{
SqlSession sqlSession = SqlSessionUtil.openSession(true);
int result = sqlSession.delete("dept.deleteByDeptNo",40);
sqlSession.close();
System.out.println("本次删除了"+result+"个部门");
}
@Test
public void test2()throws Exception{
SqlSession sqlSession = SqlSessionUtil.openSession(true);
Dept dept = new Dept(40,"综合部","北京");
int result = sqlSession.insert("dept.insertDept",dept);
sqlSession.close();
System.out.println("本次注册了"+result+"个部门");
}



