一、第二种设置返回的结果类型 除了resultType通过填写全限定名称来指定返回类型,我们也可以使用resultMap它来指定返回类型,它可以指定列名的值设值给指定的java属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <resultMap id ="studentMap" type ="com.apps.bean.Student" > <id column ="id" property ="id" /> <result column ="name" property ="name" /> <result column ="email" property ="email" /> <result column ="age" property ="age" /> </resultMap > <select id ="selectAllStudents" resultMap ="studentMap" > select * from stu; </select > 这样就可以指定列名的值设值给指定的java属性,如我们要 把数据库中的email字段值 设值给 javaa对象的name属性 时,就可以这样写 <resultMap id ="studentMap" type ="com.apps.bean.Student" > <id column ="id" property ="id" /> <result column ="name" property ="email" /> <result column ="email" property ="name" /> <result column ="age" property ="age" /> </resultMap > <select id ="selectAllStudents" resultMap ="studentMap" > select * from stu; </select >
二、解决方式 1.1 第一种:定义resultMap 使用resultMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /* 接口 */ List<MyStudent > selectMyStudent(); /* mapper文件 */ MyStudent为新定义的java类,它的属性名跟数据库中的字段名是不一样的 <resultMap id ="myStudentMap" type ="com.apps.bean.MyStudent" > <id column ="id" property ="myId" /> <result column ="name" property ="myName" /> <result column ="email" property ="myEmail" /> <result column ="age" property ="myAge" /> </resultMap > <select id ="selectMyStudent" resultMap ="myStudentMap" > select * from stu; </select >
1.2 第二种:列别名 resultType的默认原则是同名的列值赋值给同名的属性,使用列别名(java类的属性名)
1 2 3 <select id ="selectDiffColProperty" resultType ="com.apps.bean.MyStudent" > select id as myId,name as myName,email as myEmail,age as myAge from stu; </select >