MyBatis返回对象问题

hibernate123 2014-08-22 11:03:17
StudentMap指定resultType="Student",parameterType="java.lang.String" sql语句为select * from Student where stunum=#{stunum}。我想知道MyBatis怎么能将查询出的一行Student信息的每一栏对应实体对象的每个属性。MyBatis又没有像Hibernate可以配置映射文件?新手求教学
...全文
1925 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
helloworl2077 2016-11-04
  • 打赏
  • 举报
回复
顶楼主,正好用到了
hibernate123 2014-09-20
  • 打赏
  • 举报
回复
自己来吧 是怪自己当时根本没有学明白。在使用MyBatis写DAO的实现也就是对应的XML文件时,当制定resultType为实体时,有两种方法可以使返回的数据库中的数据跟实体中每个属性对应 第一种:在写SELECT语句的时候,顺便写上查出的数据的列名称对应的实体属性。如: select student_id as id, student_name as name, student_sex as sex from studnetTable where studnet_id=#{id} 注意前面是数据库中列名,后面是项目中自己建的实体的属性名称。顺便提一下,#{id}表示传入的参数,传参可以是以实体为载体,也可以map为载体,也可以为普通数据类型,比如String,int等。 第二种:将查出的数据的列名称对应的实体属性单独定义,形式为<resultMap>...</resultMap>。如: <resultMap id="ResultMap1" type="model.student"> <id column="student_id" property="id" jdbcType="VARCHAR" /> <result column="studnet_name" property="name" jdbcType="VARCHAR" /> <result column="student_sex" property="sex" jdbcType="VARCHAR" /> </resultMap> 然后在写SELECT语句时,就可以引用了,例如: <select id="queryStudnetInfo" resultMap="ResultMap1"> select * from department where student_id=#{id,jdbcType=VARCHAR} </select> 大家应该注意到了,resultMap中引用了定义好的对应关系的结果,这样就可以成功查询到了。 顺便提一下,id="queryStudnetInfo",这个queryStudnetInfo是在DAO中定义的接口,具体代码为: Studnet queryStudnetInfo(String id);

5,657

社区成员

发帖
与我相关
我的任务
社区描述
Web开发应用服务器相关讨论专区
社区管理员
  • 应用服务器社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧