2.3 < resultMap >标签
如果数据表中字段的名称和Java实体类中属性的名称不一致,就要使用< resultMap>标签来进行映射。
创建名为resultMapTest的Java项目,映射配置文件userinfoMapping.xml代码如下。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd">
<mapper namespace="mybatis.testcurd">
<resultMap type="entity.Userinfo" id="userinfo">
<result column="id" property="idghy" />
<result column="username" property="usernameghy" />
<result column="password" property="passwordghy" />
<result column="age" property="ageghy" />
<result column="insertdate" property="insertdateghy" />
</resultMap>
<select id="getUserinfoAll" resultMap="userinfo">
select * from
userinfo
</select>
</mapper>```
实体类Userinfo.java的结构如图2-1所示。
<div style="text-align: center"><img src="https://yqfile.alicdn.com/eb1953f6ef12b87f9406f28874dcce16a0abac7f.png" width="" height="">
</div>
创建Run.java运行类,核心代码如下。
public class Run {
public static void main(String[] args) {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List listUserinfo = sqlSession
.selectList("getUserinfoAll");
for (int i = 0; i < listUserinfo.size(); i++) {
Userinfo userinfo = listUserinfo.get(i);
System.out.println(userinfo.getIdghy() + " "
+ userinfo.getUsernameghy() + " "
+ userinfo.getPasswordghy() + " "
+ userinfo.getAgeghy() + " "
+ userinfo.getInsertdateghy());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
运行程序后的结果如图2-2所示。
本文仅用于学习和交流目的,不代表异步社区观点。非商业转载请注明作译者、出处,并保留本文的原始链接。
时间: 2024-09-23 06:49:53