1.resultType
期望从这条语句中返回结果的类全限定名或别名。 注意,如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身的类型。 并且resultType 和 resultMap 之间只能同时使用一个。
resultType结果类型, 指sql语句执行完毕后, 数据转为的java对象, java类型是任意的。
处理方式:
- mybatis执行sql语句, 然后mybatis调用类的无参数构造方法,创建对象。
- mybatis把ResultSet指定列值付给同名的属性。
例如:
<select id="selectMultiPosition" resultType="com.bjpowernode.domain.Student">
select id,name, email,age from student
</select>
对等的jdbc:
ResultSet rs = executeQuery(" select id,name, email,age from student" )
while(rs.next()){
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"))
}
2.resultMap:结果映射
resultMap:结果映射, 指定列名和java对象的属性对应关系。即可以自定义列名赋值给哪个属性,当你的列名和属性名不一样时使用。
resultMap
元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets
数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap
能够代替实现同等功能的数千行代码。resultMap
的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
使用方式:
- 先定义 resultMap,指定列名和属性的对应关系。
- 在 < select > 中把 resultType 替换为 resultMap
接口方法:
List<Student> selectAllStudents();
mapper文件:
<resultMap id="studentMap" type="com.domain.Student">
<id column="id" property="id"/>
<!--对于非主键列,使用result-->
<result column="name" property="name"/>
<result column="email" property="email"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectAllStudents" resultMap="studentMap">
select id,name,email,age from student
</select>
测试方法:
@Test
public void testSelectAllStudent(){
SqlSession sqlSession= MyBatisUtils.getSqlSession();
StudentDao dao=sqlSession.getMapper(StudentDao.class);
List<Student> students=dao.selectAllStudents();
for (Student stu : students) {
System.out.println(stu);
}
sqlSession.close();
}
解释:
property
:映射到列结果的字段或属性。如果 JavaBean 有这个名字的属性(property),会先使用该属性。否则 MyBatis 将会寻找给定名称的字段(field)。 无论是哪一种情形,你都可以使用常见的点式分隔形式进行复杂属性导航。 比如,你可以这样映射一些简单的东西:“username”,或者映射到一些复杂的东西上:“address.street.number”。
column
:数据库中的列名,或者是列的别名。一般情况下,这和传递给 resultSet.getString(columnName) 方法的参数一样。
3.模糊like
模糊查询的实现有两种方式, 一是 java 代码中给查询数据加上“%” ; 二是在 mapper 文件 sql 语句的条件位置加上“%”
示例:
接口方法:
List<Student> selectLike(String name);
mapper文件:
<select id="selectLike" resultType="com.domain.Student">
select id,name,email,age from student where name like #{name}
</select>
测试方法:
@Test
public void testSelectLike(){
SqlSession sqlSession= MyBatisUtils.getSqlSession();
StudentDao dao=sqlSession.getMapper(StudentDao.class);
String name="%张%";
List<Student> students=dao.selectLike(name);
for (Student stu : students) {
System.out.println(stu);
}
sqlSession.close();
}