生活随笔
收集整理的這篇文章主要介紹了
MyBatis笔记——配置文件完成增删改查
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
l 完成品牌數據的增刪改查操作
§ 要完成的功能列表清單:□ 查詢? 查詢所有數據? 查看詳情? 條件查詢□ 添加□ 修改? 修改全部字段? 修改動態字段□ 刪除? 刪除一個? 批量刪除準備環境:§ 數據庫表tb_brand
drop table if exists tb_brand
;CREATE TABLE tb_brand
(id
int PRIMARY KEY auto_increment,brand_name
varchar(20),company_name
varchar(20),ordered
int,description
varchar(100),status int
);
insert into tb_brand
(brand_name
, company_name
, ordered
, description
, status) values
('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火',0),
('華為', '華為技術有限公司', 100, '華為致力于構建萬物互聯的智能世界',1),
('小米', '小米科技有限公司', 50, 'are you ok',1);select * from tb_brand
;
§ 實體類Brand§ 測試用例§ 安裝MybatisX插件□ MybatisX是一款基于IDEA的快速開發插件,為效率而生。□ 主要功能:? XML和接口方法相互跳轉? 根據接口方法生成statrment□ 安裝:
接口:BrandMapper.java
import com.itheima.Pojo.Brand;
import org.apache.ibatis.annotations.Param;import java.util.List;
import java.util.Map;public interface BrandMapper {List<Brand> selectAll();Brand selectById(int id
);
List<Brand> selectByCondition(Map map
);List<Brand> selectByConditionSingle(Brand brand
);void add(Brand brand
);int update(Brand brand
);int deleteById(int id
);int deleteByIds(@Param("ids")int[] ids
);
}
BrandMapper.xml配置文件
<?xml version
="1.0" encoding
="UTF-8" ?>
<!DOCTYPE mapperPUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--namespace
:名稱空間
-->
<mapper namespace
="com.itheima.mapper.BrandMapper"><!--數據庫表的字段名稱 和 實體類的屬性名稱不一樣,則不能自動封裝
*起別名:給不一樣的列名起別名,讓列名和實體類的屬性名一樣
*缺點:每次查詢都要定義一次別名
*<使用sql片段可以解決
>*缺點:不靈活
*resultMap:
1.定義
<resultMap>標簽
2.在
<select>標簽中,使用resultMap屬性替換resultType
--><resultMap id
="brandResultMap" type
="Brand"><!--id
:完成主鍵字段的映射column:表的列名property:實體類的屬性名result
:完成一般字段的映射column:表的列名property:實體類的屬性名
--><result column
="brand_name" property
="brandName"/><result column
="company_name" property
="companyName"/></resultMap
><!--查詢所有
--><select id
="selectAll" resultMap
="brandResultMap">select
*from tb_brand
;</select
><!--根據id查看詳情
--><!--*參數占位符:
1.#
{}: 會將其替換成
?2.$
{}: 拼sql,會存在sql注入問題
3.使用時機
*參數傳遞的時候:#
{}*表名或者列名不固定的情況下:$
{}*參數類型:parameterType可以省略
*特殊字符處理:
1.轉義字符
(<
;)轉義
"<"符號
2.CDATA區
--><select id
="selectById" resultMap
="brandResultMap">select
*from tb_brand where id
= #
{id
};</select
><!--<select id
="selectById" resultMap
="brandResultMap">select
*
&#
45;&#
45; from tb_brand where id
<
; #
{id
};<![CDATA
[<]]></select
>--><!--查詢
-多條件查詢
--><!--<select id
="selectByCondition" resultMap
="brandResultMap">select
*from tb_brandwhere status
= #
{status
}and company_name like #
{companyName
}and brand_name like #
{brandName
};</select
>--><!--動態條件查詢,動態SQL
*if 條件判斷:
*test:邏輯表達式
*有個問題就是當第一個條件不成立并且后面條件成立時sql語句就變成了where后面加and xxx
*解決方案:
1.恒等式,在where后面加一個恒等式,并且在第一個條件的執行語句前加and
2.<where>替換掉sql中的where關鍵字
--><select id
="selectByCondition" resultMap
="brandResultMap">select
*from tb_brand
<where><if test
="status != null">and status
= #
{status
}</if><if test
="companyName != null and companyName != ''">and company_name like #
{companyName
}</if><if test
="brandName != null and brandName != ''">and brand_name like #
{brandName
};</if></where
></select
><!--單條件動態查詢
--><select id
="selectByConditionSingle" resultMap
="brandResultMap">select
*from tb_brandwhere
<choose> <!--相當于
switch--><when test
="status != null">status
= #
{status
}</when
><when test
="companyName != null and companyName != ''">company_name like #
{companyName
}</when
><when test
="brandName != null and brandName != ''">brand_name like #
{brandName
}</when
><otherwise> <!--相當于
default-->1=1</otherwise
></choose
></select
><!--添加
--><insert id
="add" useGeneratedKeys
="true" keyProperty
="id">insert into
tb_brand(brand_name
, company_name
, ordered
, description
, status
)value
(#
{brandName
}, #
{companyName
}, #
{ordered
}, #
{description
}, #
{status
});</insert
><!--修改
--><!--<update id
="update">update tb_brandset brand_name
= #
{brandName
},company_name
= #
{companyName
},ordered
= #
{ordered
},description
= #
{description
},status
= #
{status
}where id
= #
{id
};</update
>--><!--動態修改
--><update id
="update">update tb_brand
<set><if test
="brandName != null and brandName != ''">brand_name
= #
{brandName
},</if><if test
="companyName != null and companyName != ''">company_name
= #
{companyName
},</if><if test
="ordered != null">ordered
= #
{ordered
},</if><if test
="description != null and description != ''">description
= #
{description
},</if><if test
="status != null">status
= #
{status
}</if></set
>where id
= #
{id
};</update
><!--刪除一個
--><delete id
="deleteById">delete from tb_brand where id
= #
{id
};</delete
><!--批量刪除
--><delete id
="deleteByIds">delete from tb_brand where id in
<foreach collection
="ids" item
="id" separator
="," open="(" close
=")">#
{id
}</foreach
></delete
><!--sql片段
--><!--<sql id
="brand_column">id
, brand_name as brandName
, company_name as companyName
, ordered
, description
, status
</sql
><select id
="selectAll" resultType
="Brand">select
<include refid
="brand_column"/>from tb_brand
;</select
><
;!&ndash
;statement
&ndash
;>
;<select id
="selectAll" resultType
="Brand">select
*from tb_brand
;</select
>--></mapper
>
測試代碼:
import com.itheima.Pojo.Brand;
import com.itheima.mapper.BrandMapper;
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 org.junit.Test;import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class MybatisTest {@Testpublic void testSelectAll() throws Exception {String resource
= "mybatis-config.xml";InputStream inputStream
= Resources.getResourceAsStream(resource
);SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);SqlSession sqlSession
= sqlSessionFactory
.openSession();BrandMapper brandMapper
= sqlSession
.getMapper(BrandMapper.class);List<Brand> brands
= brandMapper
.selectAll();System.out
.println(brands
);sqlSession
.close();}@Testpublic void testSelectById() throws Exception {int id
= 1;String resource
= "mybatis-config.xml";InputStream inputStream
= Resources.getResourceAsStream(resource
);SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);SqlSession sqlSession
= sqlSessionFactory
.openSession();BrandMapper brandMapper
= sqlSession
.getMapper(BrandMapper.class);Brand brand
= brandMapper
.selectById(id
);System.out
.println(brand
);sqlSession
.close();}@Testpublic void testSelectByCondition() throws Exception {int status
= 1;String companyName
= "華為";String brandName
= "華為";companyName
= "%" + companyName
+ "%";brandName
= "%" + brandName
+ "%";Map<Object, Object> map
= new HashMap<Object, Object>();map
.put("status", status
);
String resource
= "mybatis-config.xml";InputStream inputStream
= Resources.getResourceAsStream(resource
);SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);SqlSession sqlSession
= sqlSessionFactory
.openSession();BrandMapper brandMapper
= sqlSession
.getMapper(BrandMapper.class);List<Brand> brands
= brandMapper
.selectByCondition(map
);System.out
.println(brands
);sqlSession
.close();}@Testpublic void testSelectByConditionSingle() throws Exception {int status
= 1;String companyName
= "華為";String brandName
= "華為";companyName
= "%" + companyName
+ "%";brandName
= "%" + brandName
+ "%";Brand brand
= new Brand();brand
.setStatus(status
);brand
.setCompanyName(companyName
);brand
.setBrandName(brandName
);String resource
= "mybatis-config.xml";InputStream inputStream
= Resources.getResourceAsStream(resource
);SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);SqlSession sqlSession
= sqlSessionFactory
.openSession();BrandMapper brandMapper
= sqlSession
.getMapper(BrandMapper.class);List<Brand> brands
= brandMapper
.selectByConditionSingle(brand
);System.out
.println(brands
);sqlSession
.close();}@Testpublic void testAdd() throws Exception {int status
= 1;String companyName
= "香飄飄食品有限公司";String brandName
= "香飄飄";int ordered
= 100;String description
= "一年銷量繞地球三圈";
Brand brand
= new Brand();brand
.setBrandName(brandName
);brand
.setCompanyName(companyName
);brand
.setOrdered(ordered
);brand
.setDescription(description
);brand
.setStatus(status
);String resource
= "mybatis-config.xml";InputStream inputStream
= Resources.getResourceAsStream(resource
);SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);SqlSession sqlSession
= sqlSessionFactory
.openSession(true);BrandMapper brandMapper
= sqlSession
.getMapper(BrandMapper.class);brandMapper
.add(brand
);Integer i
= brand
.getId();System.out
.println(i
);
sqlSession
.close();}@Testpublic void testUpdate() throws Exception {int id
= 11;int status
= 1;String companyName
= "香飄飄食品有限公司";String brandName
= "香飄飄";int ordered
= 200;String description
= "香飄飄超好喝,一年銷量繞地球三圈";
Brand brand
= new Brand();brand
.setId(id
);
brand
.setOrdered(ordered
);
String resource
= "mybatis-config.xml";InputStream inputStream
= Resources.getResourceAsStream(resource
);SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);SqlSession sqlSession
= sqlSessionFactory
.openSession(true);BrandMapper brandMapper
= sqlSession
.getMapper(BrandMapper.class);int count
= brandMapper
.update(brand
);System.out
.println(count
);
sqlSession
.close();}@Testpublic void testDeleteById() throws Exception {int id
= 11;String resource
= "mybatis-config.xml";InputStream inputStream
= Resources.getResourceAsStream(resource
);SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);SqlSession sqlSession
= sqlSessionFactory
.openSession(true);BrandMapper brandMapper
= sqlSession
.getMapper(BrandMapper.class);int count
= brandMapper
.deleteById(id
);System.out
.println(count
);
sqlSession
.close();}@Testpublic void testDeleteByIds() throws Exception {int[] ids
= {1, 2};String resource
= "mybatis-config.xml";InputStream inputStream
= Resources.getResourceAsStream(resource
);SqlSessionFactory sqlSessionFactory
= new SqlSessionFactoryBuilder().build(inputStream
);SqlSession sqlSession
= sqlSessionFactory
.openSession(true);BrandMapper brandMapper
= sqlSession
.getMapper(BrandMapper.class);int count
= brandMapper
.deleteByIds(ids
);System.out
.println(count
);
sqlSession
.close();}
}
總結
以上是生活随笔為你收集整理的MyBatis笔记——配置文件完成增删改查的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。