输出映射(例如一个方法的返回至使用什么类型去接收)

1.基本类型

     <!-- 统计记录数 -->
<select id="queryTotalCount" resultType="long">
SELECT COUNT(*) FROM t_customer
</select>

public Long queryTotalCount();

    /**
* 输出映射
*/
@Test
public void test2() {
SqlSession sqlSession = SessionUtils.getSession();
// getMapper(): 返回指定接口的动态代理的实现类对象
CustomerDao dao = sqlSession.getMapper(CustomerDao.class);
Long count = dao.queryTotalCount();
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}

2.JavaBean类型(*常用类型)

     <select id="queryCustomer" parameterType="int" resultType="Customer">
SELECT * FROM t_customer WHERE id=#{value}
</select>

public Customer queryCustomer(Integer id);

     /**
* 输出映射
*/
@Test
public void test2() {
SqlSession sqlSession = SessionUtils.getSession();
// getMapper(): 返回指定接口的动态代理的实现类对象
CustomerDao dao = sqlSession.getMapper(CustomerDao.class);
Customer c = dao.queryCustomer(1);
System.out.println(c);
sqlSession.commit();
sqlSession.close();
}

3.ResultMap类型(用于解决表的字段名称和实体类的属性名称不一致的情况)

resultType使用要求:JavaBean中的属性名要和数据库字段名保持一致。

     <!-- 定义ResultMap -->
<!--
含义说明:
type:我们需要封装成的实体类
id:定义的名称,供下方代码使用
-->
<resultMap type="CustomerRM" id="customerResultMap">
<!--
id:映射主键
column:数据库字段
property:实体类中的命名
-->
<id column="id" property="custId"/>
<result column="name" property="custName"/>
<result column="gender" property="custGender"/>
<result column="telephone" property="custTelephone"/>
</resultMap>
     <select id="queryCustomerResultMap" parameterType="int" resultMap="customerResultMap">
<!-- resultMap:方法的返回值类型,也就是上方定义的type="CustomerRM"中的CustomerRM对象 -->
SELECT * FROM t_customer WHERE id=#{value}
</select>
     /**
* 输出映射
*/
@Test
public void test2() {
SqlSession sqlSession = SessionUtils.getSession();
// getMapper(): 返回指定接口的动态代理的实现类对象
CustomerDao dao = sqlSession.getMapper(CustomerDao.class);
CustomerRM c = dao.queryCustomerResultMap(1);
System.out.println(c);
sqlSession.commit();
sqlSession.close();
}

CustomerRM.java:

 package cn.sm1234.domain;

 public class CustomerRM {

     private Integer custId;
private String custName;
private String custGender;
private String custTelephone;
public Integer getCustId() {
return custId;
}
public void setCustId(Integer custIid) {
this.custId = custIid;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustGender() {
return custGender;
}
public void setCustGender(String custGender) {
this.custGender = custGender;
}
public String getCustTelephone() {
return custTelephone;
}
public void setCustTelephone(String custTelephone) {
this.custTelephone = custTelephone;
}
@Override
public String toString() {
return "CustomerRM [custId=" + custId + ", custName=" + custName + ", custGender=" + custGender
+ ", custTelephone=" + custTelephone + "]";
} }

数据库字段截图:

Mybatis进阶学习笔记——输出映射-LMLPHP

05-02 12:33