Mybatis中实体类别名、多参数、动态SQL的示例分析

发布时间:2021-09-14 17:50:13 作者:小新
来源:亿速云 阅读:127

这篇文章主要介绍了Mybatis中实体类别名、多参数、动态SQL的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

一、说明

开始讲实体类别名、多参数、动态SQL等

二、开搞

数据库表

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, '广州', '程序屌丝');

2.1 实体类别名

2.1.1 第一种方式
1.创建实体类
package entity;

import java.math.BigDecimal;

/**
 * @author 发现更多精彩  关注公众号:木子的昼夜编程
 * 一个生活在互联网底层,做着增删改查的码农,不谙世事的造作
 * @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.创建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.使用别名
<!--根据主键查询-->
<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);
            // 查询数据
            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默认别名

映射类型
_bytebyte
_longlong
_shortshort
_intint
_integerint
_doubledouble
_floatfloat
_booleanboolean
stringString
byteByte
longLong
shortShort
intInteger
integerInteger
doubleDouble
floatFloat
booleanBoolean
dateDate
decimalBigDecimal
bigdecimalBigDecimal
objectObject
mapMap
hashmapHashMap
listList
arraylistArrayList
collectionCollection
iteratorIterator

2.2 插入数据返回自增主键

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());
        }
    }
}

输出结果:

Mybatis中实体类别名、多参数、动态SQL的示例分析

主键不是直接返回的,而是把主键值设置到插入的对象里的

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 多参数

2.3.1 一个参数
// 根据主键查询
TestEntity get(Long id);
<!--根据主键查询-->
<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>

如果只有一个参数,并且参数类型是Java基础类型或String类型,那么使用这个参数的时候

#{xxoo} xxoo可以是任意字符 与方法输入参数名称无关

上边例子中:id、xx、oo、aaabbb 都可以使用 ,但是哈,我们一般见名知意,传递的什么参数(id),我们xml就用#{传递的参数} 这不是必须但可以遵循这个规范

2.3.2 多个参数 之实体类
// 新增
void save(TestEntity testEntity);
<!--增加-->
<insert id="save">
    INSERT INTO `test`(`name`, `salary`) VALUE (#{name}, #{salary})
</insert>

这个很容易明白,实体类参数叫什么 这里#{}里边就用什么

2.3.3 多个参数之@Param注解
// 根据名称模糊查询
List<TestEntity> listByNameAndAge(@Param("name") String name,@Param("age") Integer age);
<!--根据名称和年龄查寻-->
<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 多个参数之Map

用Map跟用实体类差不多 就key值当做是实体类的字段名称就可以

// 多参数Map 方式传递
List<TestEntity> listByNameAndAgeMap(Map<String, Object> param);
<!--param多参数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 多个参数之默认

默认有两套参数:

arg0、arg1、arg2、argxxx ; arg从0开始按照方法参数顺序

param1、param2、param3、paramxxx ; param从1开始按照方法参数顺序

// 什么都不用
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 数组参数之基础值&实体类

注意传递数组的话,默认参数名称为arry

1. 根据多个年龄查询数据:
// 根据年龄集合查询
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. 根据名称和年龄多条件查询

例如:名称是小强并且年龄是19 或者名称是小月月年龄是20 的数据

// 根据多组参数查询
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 集合参数之基础值&实体类

集合与数组差不多,但还是有点儿差别

不同点1: 集合如果不指定参数名称的话默认使用:collection或者list 不是array

不同点2:集合判断大小是这样的 用的size() 不是length

 <if test="list != null and list.size() >0"></if>

2.4 四大标签的说明

select是Mybatis使用最多的标签之一,他与insert update delete不同,他不对数据库值做改变,只是查

insert、 update、 delete 会对数据库的值做变更,这三个标签可以混用,也就是说他们功能一样,出三个的意义就是为了业务上可以区分一下是新增、修改还是删除。一般我们也遵循这个使用。

感谢你能够认真阅读完这篇文章,希望小编分享的“Mybatis中实体类别名、多参数、动态SQL的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

推荐阅读:
  1. MyBatis动态sql
  2. Mybatis之动态SQL的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatis sql

上一篇:keepalived怎么配置redis主从切换

下一篇:Linux下安装DB2的包依赖错误及解决方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》