resultType和resultMap只能有一个成立,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,resultMap解决复杂查询是的映射问题。比如:列名和对象属性名不一致时可以使用resultMap来配置;还有查询的对象中包含其他的对象等。
MyBatisConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--定义别名 注意typeAliases一定要在environments之前-->
<typeAliases>
<typeAlias type="jike.book.pojo.JiKeUser" alias="JiKeUser"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/jikebook"/>
<property name="username" value="root"/>
<property name="password" value="*****"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="jike/book/map/jikeUser.xml"/>
<mapper class="jike.book.Impl.InterfaceJikeUserMap"/>
</mappers>
</configuration>
jikeUser.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="/">
<resultMap id="JiKeUserMap" type="JiKeUser">
<id property="id" column="id"/>
<result property="userName" column="userName"/>
<result property="password" column="password"/>
</resultMap>
<select id="selectUserMap" resultMap="JiKeUserMap">
select * from jikeUser;
</select>
<select id="selectUserList" resultType="JiKeUser" parameterType="JiKeUser">
select * from jikebook.jikeuser;
</select>
</mapper>
TestSelect.java
package jike.book.test;
import jike.book.pojo.JiKeUser;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
/**
* DateTime: 2016/9/5 21:45
* 功能:
* 思路:
*/
public class TestSelect {
public static void main(String[] args) {
// 资源路径
String resource="jike/book/map/MyBatisConfig.xml";
Reader reader=null;
SqlSession session;
try {
reader= Resources.getResourceAsReader(resource);
} catch ( IOException e ) {
e.printStackTrace();
}
SqlSessionFactory sqlMapper=new SqlSessionFactoryBuilder().build(reader);
session=sqlMapper.openSession();
List<JiKeUser> list=session.selectList("selectUserMap");
// List<JiKeUser> list=session.selectList("selectUserList");
for(JiKeUser jiKeUser:list){
System.out.println(jiKeUser.getUserName());
}
session.close();
}
}
运行
List<JiKeUser> list=session.selectList("selectUserMap");
或者
List<JiKeUser> list=session.selectList("selectUserList");
结果都是一样的