在实体和数据库字段一致 时直接使用resultType时可以的。
当字段不一致时,可以使用别名。使之一致。
以下讲解使用resultMap情况。
实体Order.java
1 package pojo; 2 3 import java.util.Date; 4 5 public class Order { 6 private Integer id; 7 8 private Integer userId; 9 10 private String number; 11 12 private Date createtime; 13 14 private String note; 15 16 public Integer getId() { 17 return id; 18 } 19 20 public void setId(Integer id) { 21 this.id = id; 22 } 23 24 public Integer getUserId() { 25 return userId; 26 } 27 28 public void setUserId(Integer userId) { 29 this.userId = userId; 30 } 31 32 public String getNumber() { 33 return number; 34 } 35 36 public void setNumber(String number) { 37 this.number = number == null ? null : number.trim(); 38 } 39 40 public Date getCreatetime() { 41 return createtime; 42 } 43 44 public void setCreatetime(Date createtime) { 45 this.createtime = createtime; 46 } 47 48 public String getNote() { 49 return note; 50 } 51 52 public void setNote(String note) { 53 this.note = note == null ? null : note.trim(); 54 } 55 56 @Override 57 public String toString() { 58 return "Order [id=" + id + ", userId=" + userId + ", number=" + number + ", createtime=" + createtime 59 + ", note=" + note + "]"; 60 } 61 62 }
数据库字段:
两者user_id不一致。映射文件
OrderMapper.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"> <!-- namespace命名空间,隔离sql文件 --> <!-- #{}占位符相当于jdbc的? --> <!-- ${value} 字符串拼接 --> <!-- 动态代理开发原则 1、namespace必须是接口的全路径 2、接口的方法必须与sql的id一致 3、接口的入参与parameterType类型一致 4、接口的返回值必须与resultType类型一致 --> <mapper namespace="mapper.OrderMapper"> <!-- 定义resultMap --> <resultMap type="order" id="order_List_map"> <id property="id" column="id"/> <result property="userId" column="user_id"/> <result property="number" column="number"/> <result property="createtime" column="createtime"/> <result property="note" column="note"/> </resultMap> <!-- 引用resultMap --> <select id="getOrderList" resultMap="order_List_map"> select id, user_id, number, createtime, note from order1 </select> </mapper>
接口OrderMapper.java
package mapper; import java.util.List; import pojo.Order; public interface OrderMapper { List<Order> getOrderList(); }
测试(注:
SqlSessionFactoryUtil工具类获得SqlSessionFactory
)
@Test public void getOrderList() { SqlSession openSession = SqlSessionFactoryUtil.getSqlSessionFactory().openSession(); //获得接口实现类 OrderMapper mapper = openSession.getMapper(OrderMapper.class); List<Order> orderList = mapper.getOrderList(); for (Order order : orderList) { System.out.println(order); } openSession.close(); }