MyBatis学习存档(4)——进行CRUD操作
使用MyBatis進行數據庫的CRUD操作有2種方式:一種如之前所說的接口+xml,而另一種是通過對接口上的方法加注解(@Select @Insert @Delete @Update)
但是通常情況下不建議使用注解進行操作,原因在于MyBatis最強大的特性在于其動態sql,若使用注解則無法使用動態sql
因此此處僅僅對注解進行簡單的舉例
一、注解
<?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.mapper.UsersMapper" ><resultMap id="BaseResultMap" type="com.pojo.Users" ><id column="id" property="id" jdbcType="INTEGER" /><result column="name" property="name" jdbcType="VARCHAR" /><result column="password" property="password" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, name, password</sql><select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="Base_Column_List" />from userswhere id = #{id,jdbcType=INTEGER}</select><update id="updateByPrimaryKeySelective" parameterType="com.pojo.Users" >update users<set ><if test="name != null" >name = #{name,jdbcType=VARCHAR},</if><if test="password != null" >password = #{password,jdbcType=VARCHAR},</if></set>where id = #{id,jdbcType=INTEGER}</update><update id="updateByPrimaryKey" parameterType="com.pojo.Users" >update usersset name = #{name,jdbcType=VARCHAR},password = #{password,jdbcType=VARCHAR}where id = #{id,jdbcType=INTEGER}</update> </mapper> UsersMapper.xml package com.mapper;import org.apache.ibatis.annotations.Select;import com.pojo.Users;public interface UsersMapper {@Select("select id, name, password from users where id = #{id}")Users selectByPrimaryKey(Integer id);int updateByPrimaryKeySelective(Users record); } UsersMapper.java依舊以之前反向生成的UsersMapper為例,為顯得簡潔些,僅保留了2個方法:selectByPrimaryKey和updateByPrimaryKeySelective
打上注解的方法selectByPrimaryKey,其注解效果和xml中的一致,但updateByPrimaryKeySelective方法卻無法打上注解,原因無它,該方法使用了動態sql,而注解中無法使用動態sql
二、接口+xml
為了之后好舉例,此處重新創建了一個名為student的表,并反向生成了映射文件和實體類,并進行了些許改動
2.1 創建student表并反向生成映射文件和實體類
sql語句如下:
CREATE TABLE student(id INT PRIMARY KEY identity(1,1), name VARCHAR(20), class VARCHAR(20));反向生成步驟不再多說
2.2 更改映射文件和實體類
反向生成后會發現實體類Student報錯了,點開發現在class處報錯——class是java的關鍵字
所以我們應當將class改成clazz,這樣就不會報錯了
僅僅更改實體類是不夠的,還需將映射xml中對應的字段進行修改
最后對接口及xml進行一定的更改,最終結果如下
package com.mapper;import com.pojo.Student;public interface StudentMapper {//通過id刪除學生int deleteById(Integer id);//添加學生int insertStudent(Student record);//通過id查找學生 Student selectById(Integer id); } StudentMapper.java <?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.mapper.StudentMapper" ><resultMap id="BaseResultMap" type="com.pojo.Student" ><id column="id" property="id" jdbcType="INTEGER" /><result column="name" property="name" jdbcType="VARCHAR" /><result column="class" property="clazz" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, name, class</sql><!-- 通過id查找學生 --><select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="Base_Column_List" />from studentwhere id = #{id,jdbcType=INTEGER}</select><!-- 通過id刪除學生 --><delete id="deleteById" parameterType="java.lang.Integer" >delete from studentwhere id = #{id,jdbcType=INTEGER}</delete><!-- 添加學生 --><insert id="insertStudent" parameterType="com.pojo.Student" >insert into student (name, class)values (#{name,jdbcType=VARCHAR}, #{clazz,jdbcType=VARCHAR})</insert> </mapper> StudentMapper.xml package com.pojo;public class Student {private Integer id;private String name;private String clazz;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name == null ? null : name.trim();}public String getClazz() {return clazz;}public void setClazz(String clazz) {this.clazz = clazz == null ? null : clazz.trim();}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", clazz=" + clazz + "]";} } Student.java2.3 對數據庫進行CRUD操作
1、首先添加一個學生,代碼如下:
package com.test;import java.io.InputStream;import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.mapper.StudentMapper; import com.pojo.Student;public class TestInsert {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources類加載mybatis的配置文件InputStream is = Resources.getResourceAsStream(resource);//構建SqlSession的工廠SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//開啟SqlSessionSqlSession session = factory.openSession();//通過映射接口執行操作StudentMapper mapper = session.getMapper(StudentMapper.class);//new一個名叫張三 一年1班的學生Student stu = new Student();stu.setName("張三");stu.setClazz("一年1班");try {mapper.insertStudent(stu);//提交 session.commit();} catch (Exception e){//回滾 session.rollback();System.out.println("添加失敗");} finally {session.close();}System.out.println("添加成功");}}結果:可以從日志中看到sql語句及傳入的參數,最后輸出“添加成功”
在數據庫里查看下添加的結果:確實多了一條數據
為了之后方便操作,在此可以多添加幾條數據:
2、查詢指定id的學生,代碼如下:
package com.test;import java.io.InputStream;import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.mapper.StudentMapper; import com.pojo.Student;public class TestSelect {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources類加載mybatis的配置文件InputStream is = Resources.getResourceAsStream(resource);//構建SqlSession的工廠SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//開啟SqlSessionSqlSession session = factory.openSession();//通過映射接口執行操作StudentMapper mapper = session.getMapper(StudentMapper.class);Student student = mapper.selectById(1);System.out.println(student);session.close();}}結果如下:
3、刪除指定id的學生,代碼如下:
package com.test;import java.io.InputStream;import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.mapper.StudentMapper;public class TestDelete {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources類加載mybatis的配置文件InputStream is = Resources.getResourceAsStream(resource);//構建SqlSession的工廠SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//開啟SqlSessionSqlSession session = factory.openSession();//通過映射接口執行操作StudentMapper mapper = session.getMapper(StudentMapper.class);try {mapper.deleteById(5);//提交 session.commit();} catch (Exception e){//回滾 session.rollback();System.out.println("刪除失敗");} finally {session.close();}System.out.println("刪除成功");}}結果如下:
現在再看數據庫中的數據,發現id為5的學生已經不見了:
4、更改指定id的學生姓名
此時,StudentMapper里并沒有update相關的方法,所以需要手動添加方法。現在接口中定義updateStudentById方法,然后在xml中編寫相應的節點:使用update節點,id與方法名一致,傳入參數類型為Student類,節點內為sql語句
package com.mapper;import com.pojo.Student;public interface StudentMapper {//通過id刪除學生int deleteById(Integer id);//添加學生int insertStudent(Student record);//通過id查找學生 Student selectById(Integer id);//更改指定id學生的姓名int updateStudentById(Student student); } StudentMappe.java <?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.mapper.StudentMapper" ><resultMap id="BaseResultMap" type="com.pojo.Student" ><id column="id" property="id" jdbcType="INTEGER" /><result column="name" property="name" jdbcType="VARCHAR" /><result column="class" property="clazz" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, name, class</sql><!-- 通過id查找學生 --><select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >select <include refid="Base_Column_List" />from studentwhere id = #{id,jdbcType=INTEGER}</select><!-- 通過id刪除學生 --><delete id="deleteById" parameterType="java.lang.Integer" >delete from studentwhere id = #{id,jdbcType=INTEGER}</delete><!-- 添加學生 --><insert id="insertStudent" parameterType="com.pojo.Student" >insert into student (name, class)values (#{name,jdbcType=VARCHAR}, #{clazz,jdbcType=VARCHAR})</insert><!-- 更改指定id學生的姓名 --><update id="updateStudentById" parameterType="com.pojo.Student">update student set name = #{name} where id = #{id}</update> </mapper> StudentMapper.xml編寫測試類,先從數據庫中查詢獲得需要修改的學生信息,再更改其姓名,最后提交
package com.test;import java.io.InputStream;import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.mapper.StudentMapper; import com.pojo.Student;public class TestUpdate {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources類加載mybatis的配置文件InputStream is = Resources.getResourceAsStream(resource);//構建SqlSession的工廠SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//開啟SqlSessionSqlSession session = factory.openSession();//通過映射接口執行操作StudentMapper mapper = session.getMapper(StudentMapper.class);Student student = mapper.selectById(4);System.out.println(student);student.setName("趙六");try{mapper.updateStudentById(student);//提交 session.commit();} catch (Exception e){//回滾 session.rollback();System.out.println("更改失敗");}System.out.println("更改成功");session.close();}}結果和數據庫如下:
5、現更改需求:更改指定id學生所在的班級
又多了一個update的需求,需要再新增一個方法嗎?并不需要,只需在updateStudentById方法對應的映射sql中進行更改就可以了,這時就可以用到動態sql了
<!-- 更改指定id學生的姓名 --><update id="updateStudentById" parameterType="com.pojo.Student">update student<set><if test="name != null">name = #{name} ,</if><if test="clazz != null">class = #{clazz} ,</if></set>where id = #{id}</update>將update節點改為上述,再編寫測試類
package com.test;import java.io.InputStream;import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import com.mapper.StudentMapper; import com.pojo.Student;public class TestUpdate {public static void main(String[] args) throws Exception {//mybatis的核心配置文件String resource = "mybatis-config.xml";//使用MyBatis提供的Resources類加載mybatis的配置文件InputStream is = Resources.getResourceAsStream(resource);//構建SqlSession的工廠SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);//開啟SqlSessionSqlSession session = factory.openSession();//通過映射接口執行操作StudentMapper mapper = session.getMapper(StudentMapper.class);Student student = new Student();student.setId(4);student.setClazz("三年1班");System.out.println(student);try{mapper.updateStudentById(student);//提交 session.commit();} catch (Exception e){//回滾 session.rollback();System.out.println("更改失敗");}System.out.println("更改成功");session.close();}}先new一個Student,再set它的id和class,此時name為null,執行update操作
可以看見執行的sql為update student SET class = ? where id = ??
如果我們將name的值set為aaa,再看執行的sql語句:
可以看見執行的sql為update student SET name = ? , class = ? where id = ??
這就是動態sql,除了if外,還有choose (when, otherwise),trim (where, set),foreach,這些節點的使用方式與JSTL標簽的使用類似
三、動態sql
3.1 if
最簡單的節點,只需配置test屬性即可,test內為布爾表達式,為true時if語句塊中的sql語句才會存在,且不會對sql進行任何變動,因此有時會出現多逗號、and、or、where的情況,通常與對應的節點使用,如set、where等
3.2 choose (when, otherwise)
choose節點下有2個子節點when和otherwise,when節點中有1個屬性test,和if的類似
該節點的語法與if...else if...else類似
<choose><when test="表達式1">sql語句1</when><when test="表達式2">sql語句2</when><otherwise>sql語句3</otherwise> </choose>例如上述例子,當表達式1為true時,有且僅有sql語句1會被執行,不會有2和3;當表達式1、2都不滿足時,就會執行sql語句3
3.3 trim
有4個屬性:prefix、suffix、prefixOverrides、suffixOverrides。它可以更靈活地去除多余關鍵字,可以替代where和set
以2.5中的sql語句為例,可變更如下,效果是一樣的:
<!-- 更改指定id學生的姓名 --><update id="updateStudentById" parameterType="com.pojo.Student">update student<trim prefix="set" suffixOverrides="," suffix="where id = #{id}"> <if test="name != null">name = #{name},</if><if test="clazz != null">class = #{clazz},</if></trim></update>3.4 foreach
用于迭代一個集合,通常用于in條件,其屬性如下:
item:集合名稱(傳入的變量名)
index:指定迭代次數的名稱
collection:必須指定,表示傳入的集合是什么類型的
list
array
map-key
open:語句的開始
separator:每次循環的分割符
close:語句的結束
轉載于:https://www.cnblogs.com/s1165482267/p/8038590.html
總結
以上是生活随笔為你收集整理的MyBatis学习存档(4)——进行CRUD操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用 Skeleton Screen 提
- 下一篇: GC 年轻代 老年代 持久代