一、Mybatis增刪改查案例
上一節《Mybatis入門和簡單Demo》講了如何Mybatis的由來,工作流程和一個簡單的插入案例,本節主要繼上一講完整的展示Mybatis的CRUD操作(重復的動作如環境搭建,引入依賴,mybatis.xml的配置,通用加載工具類的編寫等參照上一節。
(1)編寫需要CRUD操作的實體類Student
package com.jyk.mybatis.crud; public class Student { private String id; private String name; private String age; private String sex; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Student(String id, String name, String age, String sex) { super(); this.id = id; this.name = name; this.age = age; this.sex = sex; } public Student() { super(); } }
(2)配置用於編寫SQL語句的StudentMapper文件(路徑com/jyk/mybatis/crud/StudentMapper.xml),並將mapper文件路徑以及實體類別名加入到mybatis總配置文件中
<?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"> <mapper namespace="com.jyk.mybatis.crud.Student"> <!-- 當實體屬性名與表字段名不一樣時,以下代碼必須書寫 當實體屬性名與表字段名一樣時,以下代碼可選 --> <resultMap type="crudstudent" id="studentMap"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> <result property="sex" column="sex"/> </resultMap> <!-- 添加操作 --> <insert id="add" parameterType="crudstudent"> insert into student(id,name,age,sex) values(#{id},#{name},#{age},#{sex}) </insert> <!-- 根據id查詢操作: 如果參數不是一個實體,只是一個普通參數,例如int,double,string 這里的#{中間的變量名可以隨便寫},不過建議用方法的形式參數 --> <select id="findById" parameterType="int" resultType="crudstudent"> select id,name,age,sex from student where id = #{id} </select> <!-- 查詢所有操作 --> <select id="findall" resultType="crudstudent"> select id,name,age,sex from student </select> <!-- 更新操作 --> <update id="update" parameterType="crudstudent"> update student set name=#{name},age=#{age},sex=#{sex} where id=#{id} </update> <!-- 刪除操作 --> <delete id="delete" parameterType="crudstudent"> delete from student where id=#{id} </delete> <!-- 增刪改查注意事項 :insert/update/delete標簽只是一個模板,在做操作時,其實是以sql語句為核心的 即當做增/刪/改時,insert/update/delete標簽可通用,但是提倡做什么操作就使用什么標簽 但做查詢時只能使用select標簽 --> <!-- mybatis會將查詢出來的表記錄和resultMap值對應的映射結果互相匹配 --> <select id="findById" parameterType="int" resultMap="studentMap"> select id,name,age,sex from student where id = #{id} </select> </mapper>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 加載類路徑下的屬性文件 --> <properties resource="db.properties"> </properties> <!-- 設置類型別名 --> <typeAliases> <typeAlias type="com.jyk.mybatis.crud.Student" alias="crudstudent"/> <!-- <typeAlias type="com.jyk.mybatis.page.Student" alias="pagestudent"/> <typeAlias type="com.jyk.mybatis.dynamic.Student" alias="dynamicstudent"/> --> </typeAliases> <!-- 設置一個默認的連接環境信息 --> <environments default="mysql_env"> <!-- 連接環境信息,取一個唯一的編號 --> <environment id="mysql_env"> <!-- mybatis使用的jdbc事務管理方式 --> <transactionManager type="jdbc"> </transactionManager> <!-- mybatis使用連接池方式來獲取鏈接 --> <dataSource type="pooled"> <!-- 配置與數據庫交互的四個屬性 --> <property name="driver" value="${mysql.driver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/jyk/mybatis/crud/StudentMapper.xml"/> <!-- <mapper resource="com/jyk/mybatis/page/StudentMapper.xml"/> <mapper resource="com/jyk/mybatis/dynamic/StudentMapper.xml"/> --> </mappers> </configuration>
(3)編寫DAO,通過Java代碼控制Mybatis進行增刪改查,MyBatisUtil的編寫參照上一節
package com.jyk.mybatis.crud; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.jyk.mybatis.util.MyBatisUtil; public class StudentDao { /* * 增加的方法1 */ public void add(Student stu) { SqlSession sqlSession = null; try{ sqlSession = MyBatisUtil.getSqlSession(); int i = sqlSession.insert(Student.class.getName()+".add", stu); System.out.println("本次操作影響了"+i+"行數據"); //事務提交 sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); //事務回滾 sqlSession.rollback(); throw e; }finally{ MyBatisUtil.closeSqlSession(); } } /* * 根據ID查找 */ public Student findById(int id) { SqlSession sqlSession = null; try{ sqlSession = MyBatisUtil.getSqlSession(); Student stu = sqlSession.selectOne(Student.class.getName()+".findById", id); return stu; }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MyBatisUtil.closeSqlSession(); } } /* * 查詢所有學生 */ public List<Student> findall() { SqlSession sqlSession = null; try{ sqlSession = MyBatisUtil.getSqlSession(); return sqlSession.selectList(Student.class.getName()+".findall"); }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MyBatisUtil.closeSqlSession(); } } /* * 更新學生信息 */ public void update(Student stu) { SqlSession sqlSession = null; try{ sqlSession = MyBatisUtil.getSqlSession(); sqlSession.update(Student.class.getName()+".update", stu); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MyBatisUtil.closeSqlSession(); } } /* * 刪除操作 */ public void delete(Student stu) { SqlSession sqlSession = null; try{ sqlSession = MyBatisUtil.getSqlSession(); sqlSession.update(Student.class.getName()+".delete", stu); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); throw e; }finally{ MyBatisUtil.closeSqlSession(); } } }
上面增刪改查操作案例需要關心的幾個地方:
(1)mapper文件的名稱需要唯一,所以一般以操作的實體類全路徑為名稱空間
(2)當實體屬性名與表字段名不一樣時,resultMap必須書寫,當實體屬性名與表字段名一樣時,resultMap可選,resultMap的type代表參數的類型,可供parameterType,resultType直接名稱引用,id作為唯一標識,可被resultMap使用
(3)如果參數不是一個實體,只是一個普通參數,例如int,double,string,這里的#{中間的變量名可以隨便寫},不過建議用方法的形式參數
<select id="findById" parameterType="int" resultType="crudstudent"> select id,name,age,sex from student where id = #{id} </select>
(4)增刪改查注意事項 :insert/update/delete標簽只是一個模板,在做操作時,其實是以sql語句為核心的,即當做增/刪/改時,insert/update/delete標簽可通用,但是提倡做什么操作就使用什么標簽,但做查詢時只能使用select標簽
(5)parameterType:指入參類型,可引用resultMap的type屬性
resultType:指出參類型,可引用resultMap的id屬性
resultMap:mybatis會將查詢出來的表記錄和resultMap值對應的映射結果互相匹配
