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();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章