1. 程式人生 > 其它 >MyBatis 對映檔案

MyBatis 對映檔案

技術標籤:mybatis

1、簡介

對映檔案指導著MyBatis如何進行資料庫增刪改查,有著非常重要的意義

2、演示

去com.atguigu.mybatis.dao下面去寫增刪改查方法(定義好即可)

package com.atguigu.mybatis.dao;


public interface DepartmentMapper {
	
	public Department getDeptById(Integer id);
	
	public Department getDeptByIdPlus(Integer id);

	public Department getDeptByIdStep(Integer id);
}

對映檔案中,為上面定義的方法新增內容

工程路徑\conf\com\atguigu\mybatis\dao

<mapper namespace="com.atguigu.mybatis.dao.DepartmentMapper">
	<!--public Department getDeptById(Integer id);  -->
	<select id="getDeptById" resultType="com.atguigu.mybatis.bean.Department">
		select id,dept_name departmentName from tbl_dept where id=#{id}
	</select>
<mapper/>

進入測試類 test03, 測試增刪改

package com.atguigu.mybatis.test;

public class MyBatisTest {
	@Test
	public void test03() throws IOException{
		
		SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
		//1、獲取到的SqlSession不會自動提交資料
		SqlSession openSession = sqlSessionFactory.openSession();
		
		try{
			EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
			//測試新增
			Employee employee = new Employee(null, "jerry4",null, "1");
			mapper.addEmp(employee);
			System.out.println(employee.getId());
			
			//測試修改
			//Employee employee = new Employee(1, "Tom", "
[email protected]
", "0"); //boolean updateEmp = mapper.updateEmp(employee); //System.out.println(updateEmp); //測試刪除 //mapper.deleteEmpById(2); //2、手動提交資料 openSession.commit(); }finally{ openSession.close(); } } }