一小時(shí)迅速入門(mén)Mybatis之實(shí)體類(lèi)別名與多參數(shù) 動(dòng)態(tài)SQL
一、說(shuō)明
前邊兩篇腿已經(jīng)邁進(jìn)門(mén)了,這篇開(kāi)始講實(shí)體類(lèi)別名、多參數(shù)、動(dòng)態(tài)SQL等
二、開(kāi)搞
數(shù)據(jù)庫(kù)表
DROP TABLE IF EXISTS `test`; CREATE TABLE `test` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `salary` decimal(10, 2) NOT NULL, `age` int(11) NULL DEFAULT NULL, `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `job` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 43 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of test -- ---------------------------- INSERT INTO `test` VALUES (1, '小明', 40000.00, 18, '北京', '程序猿'); INSERT INTO `test` VALUES (2, '小強(qiáng)', 50000.00, 19, '南京', '程序汪'); INSERT INTO `test` VALUES (3, '小月月', 50000.00, 20, '天津', '程序狗'); INSERT INTO `test` VALUES (4, '小月鳥(niǎo)', 40000.00, 21, '廣州', '程序?qū)沤z');
2.1 實(shí)體類(lèi)別名
2.1.1 第一種方式
1.創(chuàng)建實(shí)體類(lèi)
package entity;
import java.math.BigDecimal;
/**
* 一個(gè)生活在互聯(lián)網(wǎng)底層,做著增刪改查的碼農(nóng),不諳世事的造作
* @create 2021-08-25 22:05
*/
public class TestEntity {
private Long id;
private String name;
private BigDecimal salary;
private Integer age;
private String city;
private String job;
// get set方法省略 IntelliJ IDEA 生成快捷鍵是Alt+Inert 選擇Getter and Setter
// toString 方法省略 IntelliJ IDEA 生成快捷鍵是Alt+Inert 選擇 toString
}
2.創(chuàng)建XML
mybatis-config.xml
<?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>
<!--這里一定注意順序 -->
<typeAliases>
<typeAlias type="entity.TestEntity" alias="testEntity"/>
</typeAliases>
<!--省略environments 看前2篇 -->
<!--省略掃描 看前2篇-->
</configuration>
配置文件順序要這樣配置:
<properties>...</properties>
<settings>...</settings>
<typeAliases>...</typeAliases>
<typeHandlers>...</typeHandlers>
<objectFactory>...</objectFactory>
<objectWrapperFactory>...</objectWrapperFactory>
<plugins>...</plugins>
<environments>...</environments>
<databaseIdProvider>...</databaseIdProvider>
<mappers>...</mappers>
3.使用別名
<!--根據(jù)主鍵查詢-->
<select id="get" resultType="testEntity">
select * from test where id = #{id}
</select>
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
System.out.println(mapper);
// 查詢數(shù)據(jù)
TestEntity testEntity = mapper.get(1L);
System.out.println(testEntity);
}
}
}
2.1.2 第二種方式
掃描包路徑 mybatis-config.xml
<?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>
<!--掃描包路徑-->
<typeAliases>
<package name="entity"/>
</typeAliases>
<!--省略environments 看前2篇 -->
<!--省略掃描 看前2篇-->
</configuration>
用掃描包路徑的方式,實(shí)體類(lèi)別名默認(rèn)就是java類(lèi)首字母小寫(xiě)
例如:TestEntity --> testEntity
還可以注解指定:
@Alias("testEntityxxoo")
public class TestEntity {
// 其他省略
}
如果寫(xiě)了注解@Alias 別名就不是”testEntity”了 ,就變成”testEntityxxoo“
2.1.3 mybatis默認(rèn)別名
| 映射類(lèi)型 | |
|---|---|
| _byte | byte |
| _long | long |
| _short | short |
| _int | int |
| _integer | int |
| _double | double |
| _float | float |
| _boolean | boolean |
| string | String |
| byte | Byte |
| long | Long |
| short | Short |
| int | Integer |
| integer | Integer |
| double | Double |
| float | Float |
| boolean | Boolean |
| date | Date |
| decimal | BigDecimal |
| bigdecimal | BigDecimal |
| object | Object |
| map | Map |
| hashmap | HashMap |
| list | List |
| arraylist | ArrayList |
| collection | Collection |
| iterator | Iterator |
2.2 插入數(shù)據(jù)返回自增主鍵
2.2.1方式一
<!--增加-->
<insert id="save" useGeneratedKeys="true" keyProperty="id">
INSERT INTO `test`( `name`, `salary`) VALUE (#{name}, #{salary});
</insert>
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
// 測(cè)試id是否到了實(shí)體類(lèi)里邊
TestEntity testEntity = new TestEntity();
testEntity.setName("小鴨子");
testEntity.setSalary(new BigDecimal(100000));
mapper.save(testEntity);
System.out.println("主鍵:"+testEntity.getId());
}
}
}
輸出結(jié)果:

主鍵不是直接返回的,而是把主鍵值設(shè)置到插入的對(duì)象里的
2.2.2 方式二
<!--增加-->
<insert id="save">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO `test`(`id`, `name`, `salary`) VALUE (#{id},#{name}, #{salary})
</insert>
2.3 多參數(shù)
2.3.1 一個(gè)參數(shù)
// 根據(jù)主鍵查詢 TestEntity get(Long id);
<!--根據(jù)主鍵查詢-->
<select id="get" resultType="testEntity">
select * from test where id = #{id}
</select>
<select id="get" resultType="testEntity">
select * from test where id = #{xx}
</select>
<select id="get" resultType="testEntity">
select * from test where id = #{oo}
</select>
<select id="get" resultType="testEntity">
select * from test where id = #{aaabbb}
</select>
如果只有一個(gè)參數(shù),并且參數(shù)類(lèi)型是Java基礎(chǔ)類(lèi)型或String類(lèi)型,那么使用這個(gè)參數(shù)的時(shí)候
#{xxoo} xxoo可以是任意字符 與方法輸入?yún)?shù)名稱無(wú)關(guān)
上邊例子中:id、xx、oo、aaabbb 都可以使用 ,但是哈,我們一般見(jiàn)名知意,傳遞的什么參數(shù)(id),我們xml就用#{傳遞的參數(shù)} 這不是必須但可以遵循這個(gè)規(guī)范
2.3.2 多個(gè)參數(shù) 之實(shí)體類(lèi)
// 新增 void save(TestEntity testEntity);
<!--增加-->
<insert id="save">
INSERT INTO `test`(`name`, `salary`) VALUE (#{name}, #{salary})
</insert>
這個(gè)很容易明白,實(shí)體類(lèi)參數(shù)叫什么 這里#{}里邊就用什么
2.3.3 多個(gè)參數(shù)之@Param注解
// 根據(jù)名稱模糊查詢
List<TestEntity> listByNameAndAge(@Param("name") String name,@Param("age") Integer age);
<!--根據(jù)名稱和年齡查尋-->
<select id="listByNameAndAge" resultType="testentity">
select * from test
where 1=1
<if test="name != null">
and name like CONCAT('%',#{name},'%')
</if>
<if test="age != null">
and age = #{age}
</if>
</select>
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
List<TestEntity> list = mapper.listByNameAndAge("小強(qiáng)", 19);
System.out.println(list);
}
}
}
2.3.4 多個(gè)參數(shù)之Map
用Map跟用實(shí)體類(lèi)差不多 就key值當(dāng)做是實(shí)體類(lèi)的字段名稱就可以
// 多參數(shù)Map 方式傳遞 List<TestEntity> listByNameAndAgeMap(Map<String, Object> param);
<!--param多參數(shù)map使用-->
<select id="listByNameAndAgeMap" resultType="testentity">
select * from test
where 1=1
<if test="name != null">
and name like CONCAT('%',#{name},'%')
</if>
<if test="age != null">
and age = #{age}
</if>
</select>
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
Map<String,Object> param = new HashMap<>();
param.put("name", "小強(qiáng)");
param.put("age", 19);
List<TestEntity> list = mapper.listByNameAndAgeMap(param);
System.out.println(list);
}
}
}
2.3.5 多個(gè)參數(shù)之默認(rèn)
默認(rèn)有兩套參數(shù):
arg0、arg1、arg2、argxxx ; arg從0開(kāi)始按照方法參數(shù)順序
param1、param2、param3、paramxxx ; param從1開(kāi)始按照方法參數(shù)順序
// 什么都不用 List<TestEntity> listByNameAndAgeNone(String name, int age);
<!--用默認(rèn)順序-->
<select id="listByNameAndAgeNone" resultType="testentity">
select * from test
where 1=1
<if test="arg0 != null">
and name like CONCAT('%',#{arg0},'%')
</if>
<if test="arg1 != null">
and age = #{arg1}
</if>
</select>
<!--用默認(rèn)順序-->
<select id="listByNameAndAgeNone" resultType="testentity">
select * from test
where 1=1
<if test="param1 != null">
and name like CONCAT('%',#{param1},'%')
</if>
<if test="param2 != null">
and age = #{param2}
</if>
</select>
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
List<TestEntity> list = mapper.listByNameAndAgeNone("小月", 20);
System.out.println(list);
}
}
}
2.3.6 數(shù)組參數(shù)之基礎(chǔ)值&實(shí)體類(lèi)
注意傳遞數(shù)組的話,默認(rèn)參數(shù)名稱為arry
1. 根據(jù)多個(gè)年齡查詢數(shù)據(jù):
// 根據(jù)年齡集合查詢 List<TestEntity> listByAges(int[] ages);
<select id="listByAges" resultType="testentity">
select * from test
where 1=1
<if test="array != null and array.length >0">
and age in
<foreach collection="array" item="age" open="(" separator="," close=")">
#{age}
</foreach>
</if>
</select>
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
int[] ages = new int[]{19,20};
List<TestEntity> list = mapper.listByAges(ages);
System.out.println(list);
}
}
}
2. 根據(jù)名稱和年齡多條件查詢
例如:名稱是小強(qiáng)并且年齡是19 或者名稱是小月月年齡是20 的數(shù)據(jù)
// 根據(jù)多組參數(shù)查詢 List<TestEntity> listByNameAndAges(TestEntity[] params);
<select id="listByNameAndAges" resultType="testentity">
select * from test
where 1=1
<if test="array != null and array.length >0">
and (
<foreach collection="array" item="item" separator="or" >
(name = #{item.name} and age = #{item.age})
</foreach>
)
</if>
</select>
public class TestMain {
public static void main(String[] args) throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 通過(guò)sesson獲取Mapper 這個(gè)Mapper會(huì)編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
TestEntity[] params = new TestEntity[2];
TestEntity testEntity01 = new TestEntity();
testEntity01.setName("小強(qiáng)");
testEntity01.setAge(19);
TestEntity testEntity02 = new TestEntity();
testEntity02.setName("小月月");
testEntity02.setAge(20);
params[0] = testEntity01;
params[1] = testEntity02;
List<TestEntity> list = mapper.listByNameAndAges(params);
System.out.println(list);
}
}
}
最后輸出的sql格式是這樣的:
select* from test where 1=1 and (
(name = '小強(qiáng)' and age = 19) or
(name = '小月月' and age = 20)
)
2.3.7 集合參數(shù)之基礎(chǔ)值&實(shí)體類(lèi)
集合與數(shù)組差不多,但還是有點(diǎn)兒差別
不同點(diǎn)1: 集合如果不指定參數(shù)名稱的話默認(rèn)使用:collection或者list 不是array
不同點(diǎn)2:集合判斷大小是這樣的 用的size() 不是length
<if test="list != null and list.size() >0"></if>
2.4 四大標(biāo)簽的說(shuō)明
select是Mybatis使用最多的標(biāo)簽之一,他與insert update delete不同,他不對(duì)數(shù)據(jù)庫(kù)值做改變,只是查
insert、 update、 delete 會(huì)對(duì)數(shù)據(jù)庫(kù)的值做變更,這三個(gè)標(biāo)簽可以混用,也就是說(shuō)他們功能一樣,出三個(gè)的意義就是為了業(yè)務(wù)上可以區(qū)分一下是新增、修改還是刪除。一般我們也遵循這個(gè)使用。
2.5 嘮嘮
沒(méi)寫(xiě)動(dòng)態(tài)Sql相關(guān)的東西 后邊幾篇寫(xiě)吧
下期預(yù)告:
# {}${} 這哥倆的區(qū)別與使用
到此這篇關(guān)于一小時(shí)迅速入門(mén)Mybatis之實(shí)體類(lèi)別名與多參數(shù) 動(dòng)態(tài)SQL的文章就介紹到這了,更多相關(guān)Mybatis 動(dòng)態(tài)SQL 多參數(shù) 實(shí)體類(lèi)別名內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis通用Mapper實(shí)現(xiàn)原理及相關(guān)內(nèi)容
今天小編就為大家分享一篇關(guān)于MyBatis通用Mapper實(shí)現(xiàn)原理及相關(guān)內(nèi)容,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
SpringBoot參數(shù)校驗(yàn)Validator框架詳解
Validator框架就是為了解決開(kāi)發(fā)人員在開(kāi)發(fā)的時(shí)候少寫(xiě)代碼,提升開(kāi)發(fā)效率,Validator專(zhuān)門(mén)用來(lái)進(jìn)行接口參數(shù)校驗(yàn),今天通過(guò)本文給大家介紹SpringBoot參數(shù)校驗(yàn)Validator框架,感興趣的朋友一起看看吧2022-06-06
JAVA中Context的詳細(xì)介紹和實(shí)例分析
這篇文章主要介紹了JAVA中Context的詳細(xì)介紹和實(shí)例分析,Context是維持android各組件能夠正常工作的一個(gè)核心功能類(lèi)。如果感興趣來(lái)學(xué)習(xí)一下2020-07-07
Java中的Set接口實(shí)現(xiàn)類(lèi)HashSet和LinkedHashSet詳解
這篇文章主要介紹了Java中的Set接口實(shí)現(xiàn)類(lèi)HashSet和LinkedHashSet詳解,Set接口和java.util.List接口一樣,同樣繼承自Collection接口,它與Collection接口中的方法基本一致,并沒(méi)有對(duì)Collection接口進(jìn)行功能上的擴(kuò)充,只是比Collection接口更加嚴(yán)格了,需要的朋友可以參考下2024-01-01
基于Java+SpringBoot實(shí)現(xiàn)人臉識(shí)別搜索
人臉識(shí)別搜索技術(shù)作為現(xiàn)代計(jì)算機(jī)視覺(jué)領(lǐng)域的重要研究方向之一,已經(jīng)在多個(gè)領(lǐng)域展現(xiàn)出巨大的應(yīng)用潛力,隨著信息技術(shù)的飛速發(fā)展,人臉識(shí)別搜索在多個(gè)領(lǐng)域得到了廣泛關(guān)注和應(yīng)用,本文旨在探討人臉識(shí)別搜索技術(shù)的背景、原理以及其在實(shí)際應(yīng)用中的意義和挑戰(zhàn)2023-08-08
java實(shí)現(xiàn)圖書(shū)館管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)圖書(shū)館管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10

