参考:http://www.jb51.net/article/121482.htm
1.selectByExample和selectByExampleWithBLOBs的区别(包含Example的使用)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@Test
public void testQueryStudentExample() {
SqlSession sqlSession = sqlSessionFactory.openSession(false);
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
try {
//分页查询性别为男、并且名称中包含z的记录,第一页,每页3条记录,按性别排序
StudentExample studentExample=new StudentExample();
studentExample.or().andGenderEqualTo(1).andNameLike("%z%");
studentExample.setOffset(0);
studentExample.setLimit(3);
studentExample.setOrderByClause("GENDER DESC");
List<
Student
> list1 = studentMapper.selectByExample(studentExample);
List<
Student
> list2 = studentMapper.selectByExampleWithBLOBs(studentExample);
System.out.println(list1.get(0).getDisc());
System.out.println(list2.get(0).getDisc());
} catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
sqlSession.close();
}
}
|
结果:
原因:
由于student表中,disc字段类型为longtext,故如果想要搜索结果包含大字段类型,则必须使用selectByExampleWithBLOBs。无需检索大字段,则使用selectByExample;
2.insertSelective和insert的区别
当有部分字段未设值时,使用insertSelective:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<
SPAN
style
=
"FONT-SIZE: 14px"
>@Test
public void testInsertStudent() {
SqlSession sqlSession = sqlSessionFactory.openSession(false);
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
try {
Student s=new Student();
s.setId(java.util.UUID.randomUUID().toString().replaceAll("\\-", ""));
s.setName("zjt");
s.setGender(1);
s.setDisc("MyBatis Generator 真心好用");
studentMapper.insertSelective(s);
sqlSession.commit();
} catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
sqlSession.close();
}
}
</
SPAN
>
|
结果:
当有所有字段均已设值时,使用insert;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<
SPAN
style
=
"FONT-SIZE: 14px"
>@Test
public void testInsertStudent() {
SqlSession sqlSession = sqlSessionFactory.openSession(false);
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
try {
Student s=new Student();
s.setId(java.util.UUID.randomUUID().toString().replaceAll("\\-", ""));
s.setName("zjt");
s.setGender(1);
s.setDisc("MyBatis Generator 真心好用");
studentMapper.insertSelective(s);
sqlSession.commit();
} catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
}finally {
sqlSession.close();
}
}
</
SPAN
>
|
结果:
3.修改操作
updateByExample
如果example定义了两个字段,数据库共4个字段,则修改数据库的两个字段,其余两个字段改为null;
updateByExampleSelective
如果example定义了两个字段,数据库共4个字段,则修改数据库的两个字段,其余两个字段不动;
updateByExampleWithBLOBs
和updateByExample相比此方法可以修改大字段类型,其余性质和updateByExample相同
updateByPrimaryKey
如果record定义了两个字段,其中有一个字段是主键,数据库共4个字段,则根据主键修改数据库的两个字段,其余两个字段改为null;
updateByPrimaryKeySelective
如果record定义了两个字段,其中有一个字段是主键,数据库共4个字段,则根据主键修改数据库的两个字段,其余两个字段不动;
updateByPrimaryKeyWithBLOBs
和updateByPrimaryKey相比此方法可以修改大字段类型,其余性质和updateByPrimaryKey相同