Mybatis的自问自答
为了不占用已经理解的朋友的视觉空间,绝大多数代码的请到最下面看注解.
问1.我们用java代码可以批量更新,在mybatis的mapper里也可以用foreach标签更新,这俩啥区别?
答:java代码支持多次会连接数据库多次,而我们在foreach里只需要连接一次即可,代码看注1.
ps:这里可能会出现代码过长(超过max_allow_packet 默认4M)的情况.这就需要我们在mabatis.xml里配置batch executor..
问2.resultType和resultMap的区别?
resultType普通简单映射,resultMap提供更复杂的映射,详情见resultMap的属性元素
问3.Statement和PrepareStatement的区别?
1、Statement用于执行静态SQL语句,在执行时,必须指定一个事先准备好的SQL语句。---------------------------------原答案链接
2、PrepareStatement是预编译的SQL语句对象,sql语句被预编译并保存在对象中。被封装的sql语句代表某一类操作,语句中可以包含动态参数“?”,在执行时可以为“?”动态设置参数值。
3、使用PrepareStatement对象执行sql时,sql被数据库进行解析和编译,然后被放到命令缓冲区,每当执行同一个PrepareStatement对象时,它就会被解析一次,但不会被再次编译。在缓冲区可以发现预编译的命令,并且可以重用。
4、PrepareStatement可以减少编译次数提高数据库性能
问4.association和collection的区别?
这个问题篇幅很大,大家可以直接点击链接看association和collection的区别https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps
问5.需求变化导致表字段变化一般处理思路是什么?
1.集成(xml,mapper),据说该功能暂未公开,我在mbatis3文档上确实没看到
2.通用mapper
问6.为什么诸如Mybatis,spring等等的框架都做了那么多步骤的向下开发才会得到最后的API呢?为什么不把他们都封装起来?
对于我们很多开发者去开发项目时候我们往往需要很灵活的配置,必须创建一个sqlsession,我们可能有时候需要的工厂创建者,工厂,都是不一样的.
注1.
/**
* 循环插入
*/
@Test
public void testCRUD() {
long start = System.currentTimeMillis();
int count = 10;
for (int i=0; i< count; i++) {
String gender = i%2 == 0 ? "M" : "F";
employeeMapper.insertSelective(new Employee(null, "TestName"+i, gender, "mahuateng@baidu.com", 1));
}
long end = System.currentTimeMillis();
System.out.println("循环批量插入"+count+"条,耗时:" + (end -start )+"毫秒");
}
/**
* 单条SQL批量插入
*/
@Test
public void testBatchInsert() {
List<Employee> list = new ArrayList<Employee>();
long start = System.currentTimeMillis();
int count = 100000;
// max_allowed_packet 默认 4M,所以超过长度会报错
for (int i=0; i< count; i++) {
String gender = i%2 == 0 ? "M" : "F";
Integer did = i%2 == 0 ? 1 : 2;
Employee emp = new Employee(null, "TestName"+i, gender, "pony@baidu.com", did);
list.add(emp);
}
employeeMapper.batchInsert(list);
long end = System.currentTimeMillis();
System.out.println("批量插入"+count+"条,耗时:" + (end -start )+"毫秒");
}