mybatis----小细节

1、起别名

在MyBatis中,<typeAliases>元素用于定义类型别名,它可以将Java类名映射为一个更简短的别名,这样在映射文件中可以直接使用别名而不需要完整的类名。

下面是一个示例:

在mybatis核心配置文件中配置typeAliases标签

复制代码
<typeAliases>
  <typeAlias alias="Acount" type="duhong.entity.Account"/>
</typeAliases>

为duhong.entity.Account类指定了别名Account。

定义了这些别名后,我们可以在映射文件中直接使用这些别名来引用对应的Java类,例如:

复制代码
<resultMap id="AccountMap" type="Account">

通过使用别名,我们可以简化映射文件中的配置,并提高代码可读性和可维护性。

2、mybatis核心配置文件加载映射文件的其他方式

复制代码
<package name="duhong.dao"/>

这种声明方式,会使mybatis查找duhong/dao下对应的xml文件,不过这种方式要求xml资源目录与dao层目录一致,而且xml名称要与mapper接口名称一致。

3、#{}与${}的区别

在MyBatis中,#{} 和 ${} 用于处理SQL语句中的参数,但是它们在作用和安全性方面有所不同。

  1. #{} 语法:
    在MyBatis中,当你使用 #{} 来表示一个参数占位符时,MyBatis会在运行时将其替换为一个参数的值,并且会使用预处理语句(PreparedStatement)来处理参数。也就是说,不管参数值是什么,它都会被视为一个字符串值并且正确地转义。

    SELECT * FROM some_table WHERE id = #{id}

  2. {} 语法: 与 #{} 不同,当你使用 {} 时,MyBatis会直接将这个位置替换为变量的字面值。也就是说,如果你的变量中包含了特定的SQL关键词或结构,它将不做任何转义直接嵌入SQL语句中。

    SELECT * FROM ${tableName} WHERE column = #{value}

测试:

dao层添加接口

复制代码
//查询所有,按降序排列
List<Account> selectAllByDesc(String key);

mapper中添加查询语句

复制代码
resultMap id="AccountMap" type="duhong.entity.Account">
<id property="id" column="id"></id>
<result property="accountNumber" column="account_number"></result>
<result property="accountType" column="account_type"></result>
<result property="balance" column="balance"></result>
</resultMap>
<select id="selectAllByDesc" resultMap="AccountMap">
     select * from account ORDER BY balance ${order};
</select>

添加junit,测试

复制代码
SqlSession sqlSession= SqlSessionUtil.openSession();
 @Test
public void test(){
     AccountDao mapper = sqlSession.getMapper(AccountDao.class);
     List<Account> account = mapper.selectAllByDesc("DESC");
     for (Account account1 : account) {
         System.out.println(account);
     }
 }

将${}换成#{},执行出错,原因在于DESC是sql语句的关键字,而#{}会将参数转化为字符串。

4、模糊查询

复制代码
<select id="selectLikeAll" resultMap="AccountMap">
    select * from account where account_number like '%${key}%';
</select>

//模糊查询
List<Account> selectLikeAll(String key);

@Test
public void likeTest(){
    AccountDao accountDao=sqlSession.getMapper(AccountDao.class);
    List<Account> accounts = accountDao.selectLikeAll("1");
    System.out.println(accounts);
}

同样直接使用#{}也会出错,#{}在' '中并不会被赋值

改进方式sql中使用concat拼接字符串

复制代码
<select id="selectLikeAll" resultMap="AccountMap">
    select * from account where account_number like concat('%',#{key},'%');
</select>
相关推荐
豆角焖肉11 小时前
MyBatis多表关联查询(一对多/多对一/多对多)
mybatis·一对多·多表设计·多对多·一对一·多对一
学Linux的语莫11 小时前
Redis 的两种持久化方式:RDB 和 AOF,一次讲懂
数据库·redis·mybatis
yio_yin1 天前
MyBatis
java·前端·mybatis
無a伟1 天前
Redis事务详解:原理、实战、坑点与实践
mybatis
豆角焖肉1 天前
MyBatis延迟加载、缓存机制与注解开发
java·spring·mybatis
就改了2 天前
MyBatis核心类用法详解
java·spring boot·后端·mybatis
momo4 天前
Java+WebAI黑马知识点
java·spring boot·mybatis
snow@li4 天前
MyBatis:动态 SQL 全景梳理
数据库·sql·mybatis
就改了4 天前
Mybatis快速入门大全(详细版)
java·spring boot·mybatis
qq_171538854 天前
深入浅出 MyBatis XML:从入门到精通
xml·java·mybatis