一小時迅速入門Mybatis之實體類別名與多參數(shù) 動態(tài)SQL
一、說明
前邊兩篇腿已經(jīng)邁進門了,這篇開始講實體類別名、多參數(shù)、動態(tài)SQL等
二、開搞
數(shù)據(jù)庫表
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, '小強', 50000.00, 19, '南京', '程序汪'); INSERT INTO `test` VALUES (3, '小月月', 50000.00, 20, '天津', '程序狗'); INSERT INTO `test` VALUES (4, '小月鳥', 40000.00, 21, '廣州', '程序?qū)沤z');
2.1 實體類別名
2.1.1 第一種方式
1.創(chuàng)建實體類
package entity;
import java.math.BigDecimal;
/**
* 一個生活在互聯(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()) {
// 通過sesson獲取Mapper 這個Mapper會編程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>
用掃描包路徑的方式,實體類別名默認就是java類首字母小寫
例如:TestEntity --> testEntity
還可以注解指定:
@Alias("testEntityxxoo")
public class TestEntity {
// 其他省略
}
如果寫了注解@Alias 別名就不是”testEntity”了 ,就變成”testEntityxxoo“
2.1.3 mybatis默認別名
| 映射類型 | |
|---|---|
| _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()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
// 測試id是否到了實體類里邊
TestEntity testEntity = new TestEntity();
testEntity.setName("小鴨子");
testEntity.setSalary(new BigDecimal(100000));
mapper.save(testEntity);
System.out.println("主鍵:"+testEntity.getId());
}
}
}
輸出結果:

主鍵不是直接返回的,而是把主鍵值設置到插入的對象里的
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 一個參數(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>
如果只有一個參數(shù),并且參數(shù)類型是Java基礎類型或String類型,那么使用這個參數(shù)的時候
#{xxoo} xxoo可以是任意字符 與方法輸入?yún)?shù)名稱無關
上邊例子中:id、xx、oo、aaabbb 都可以使用 ,但是哈,我們一般見名知意,傳遞的什么參數(shù)(id),我們xml就用#{傳遞的參數(shù)} 這不是必須但可以遵循這個規(guī)范
2.3.2 多個參數(shù) 之實體類
// 新增 void save(TestEntity testEntity);
<!--增加-->
<insert id="save">
INSERT INTO `test`(`name`, `salary`) VALUE (#{name}, #{salary})
</insert>
這個很容易明白,實體類參數(shù)叫什么 這里#{}里邊就用什么
2.3.3 多個參數(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()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
List<TestEntity> list = mapper.listByNameAndAge("小強", 19);
System.out.println(list);
}
}
}
2.3.4 多個參數(shù)之Map
用Map跟用實體類差不多 就key值當做是實體類的字段名稱就可以
// 多參數(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()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
Map<String,Object> param = new HashMap<>();
param.put("name", "小強");
param.put("age", 19);
List<TestEntity> list = mapper.listByNameAndAgeMap(param);
System.out.println(list);
}
}
}
2.3.5 多個參數(shù)之默認
默認有兩套參數(shù):
arg0、arg1、arg2、argxxx ; arg從0開始按照方法參數(shù)順序
param1、param2、param3、paramxxx ; param從1開始按照方法參數(shù)順序
// 什么都不用 List<TestEntity> listByNameAndAgeNone(String name, int age);
<!--用默認順序-->
<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>
<!--用默認順序-->
<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()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
List<TestEntity> list = mapper.listByNameAndAgeNone("小月", 20);
System.out.println(list);
}
}
}
2.3.6 數(shù)組參數(shù)之基礎值&實體類
注意傳遞數(shù)組的話,默認參數(shù)名稱為arry
1. 根據(jù)多個年齡查詢數(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()) {
// 通過sesson獲取Mapper 這個Mapper會編程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ù)名稱和年齡多條件查詢
例如:名稱是小強并且年齡是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()) {
// 通過sesson獲取Mapper 這個Mapper會編程Mybatis的代理Mapper
TestMapper mapper = session.getMapper(TestMapper.class);
TestEntity[] params = new TestEntity[2];
TestEntity testEntity01 = new TestEntity();
testEntity01.setName("小強");
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 = '小強' and age = 19) or
(name = '小月月' and age = 20)
)
2.3.7 集合參數(shù)之基礎值&實體類
集合與數(shù)組差不多,但還是有點兒差別
不同點1: 集合如果不指定參數(shù)名稱的話默認使用:collection或者list 不是array
不同點2:集合判斷大小是這樣的 用的size() 不是length
<if test="list != null and list.size() >0"></if>
2.4 四大標簽的說明
select是Mybatis使用最多的標簽之一,他與insert update delete不同,他不對數(shù)據(jù)庫值做改變,只是查
insert、 update、 delete 會對數(shù)據(jù)庫的值做變更,這三個標簽可以混用,也就是說他們功能一樣,出三個的意義就是為了業(yè)務上可以區(qū)分一下是新增、修改還是刪除。一般我們也遵循這個使用。
2.5 嘮嘮
沒寫動態(tài)Sql相關的東西 后邊幾篇寫吧
下期預告:
# {}${} 這哥倆的區(qū)別與使用
到此這篇關于一小時迅速入門Mybatis之實體類別名與多參數(shù) 動態(tài)SQL的文章就介紹到這了,更多相關Mybatis 動態(tài)SQL 多參數(shù) 實體類別名內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot中的@RequestMapping注解的用法示例
@RequestMapping注解是SpringBoot中最常用的注解之一,它可以幫助開發(fā)者定義和處理HTTP請求,本篇文章我們將詳細為大家介紹如何使用SpringBoot中的@RequestMapping注解,感興趣的同學跟著小編一起來學習吧2023-06-06
Spring boot集成redis lettuce代碼實例
這篇文章主要介紹了Spring boot集成redis lettuce代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04
使用.NET Core3.0創(chuàng)建一個Windows服務的方法
這篇文章主要介紹了使用.NET Core3.0創(chuàng)建一個Windows服務的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04

