SSM框架(Spring + SpringMVC + MyBatis)学习笔记(02),第四课:MyBatis

一、Mybatis返回数据类型

1.实体对象

当需要返回整张表的信息时,可以使用实体类做为返回值类型

<!-- 范围值类型为实体对象 -->
	<select id="findAll" resultType="cn.springmybatis01.entity.Emp">
		select * from emp
	</select>
2、Map集合

当返回值只需要表中的某几列时,可以使用Map集合做为返回值类型

<select id="findMap" resultType="map">
	select name,sex from emp
</select>
3、基本类型

当范围值为单个数值,或则单列,则可以根据数值的类型定义返回值类型

<select id="count" resultType="int">
	select count(*) from emp
</select>
4、resultMap

当返回的列名和表中的列名没有对应的时候,除了使用别名

<select id="find">
		select name xingming, sex, salary from emp;
</select>
mysql> select name xingming, sex, salary from emp;
+----------+-----+-----------+
| xingming | sex | salary    |
+----------+-----+-----------+
| xiaohua  |   0 |   5000.00 |
| 小红     |   0 |   8000.00 |
| 校长     |   0 | 100000.00 |
+----------+-----+-----------+
3 rows in set (0.00 sec)

也可以使用resultMap

<select id="find2" resultMap="empMap">
	select name, sex, salary from emp;
</select>
	
<resultMap type="map" id="empMap">
	<!-- 属性名和列名相同的可以不写
	<id property="id" column="id"/>
	-->
	<result property="xingming" column="name"/>
	<!-- 属性名和列名相同的可以不写
	<result property="sex" column="sex"/>
	<result property="salary" column="salary"/>
	-->
</resultMap>

二、Mapper映射器接口

1.设置namespace的值为dao接口的路径

sql.xml文件中namespace的值为dao接口的路径

<mapper namespace="cn.springmybatis01.dao.EmpDao">
	<!--这里为具体的sql-->
</mapper>
2、编写dao文件
package cn.springmybatis01.dao;

import java.util.List;
import java.util.Map;

import cn.springmybatis01.entity.Emp;

public interface EmpDao {
	//函数的返回值类型,根据sql.xml文件中resultType确定(多行使用list);
	//函数的参数,根据sql.xml文件中parameterType确定;
	//函数名,根据sql.xml文件中id确定
	public List<Emp> findAll();
	
	public List<Map> findMap();
	
	public void updateById(int id);
	
	public List<Map> find2();
	
}

三、测试

package cn.springmybatis01.test;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import cn.springmybatis01.dao.EmpDao;
import cn.springmybatis01.entity.Emp;
import cn.springmybatis01.util.MyBatisUtil;

public class EmpTest {
	
	public static void main(String[] args) {
		SqlSession ssn = MyBatisUtil.getSqlSession();
		
		EmpDao empDao = ssn.getMapper(EmpDao.class);
		List<Emp> list = empDao.findAll();
		for(Emp emp : list) {
			System.out.println("name:"+emp.getName()+", salary:"+emp.getSalary());
		}
		
		List<Map> empList = empDao.findMap();
		for(Map map : empList) {
			System.out.println("name:"+map.get("name")+", sex:"+map.get("sex"));
		}
		
		empDao.updateById(9);
		
		List<Map> find2List = empDao.find2();
		for(Map map : find2List) {
			System.out.println("name:"+map.get("xingming")+", sex:"+map.get("sex")+", salary:"+map.get("salary"));
		}
		
		ssn.commit();
		ssn.close();
	}
}

发布了23 篇原创文章 · 获赞 5 · 访问量 1470

猜你喜欢

转载自blog.csdn.net/zj499063104/article/details/99673979