Mybatis注解方式基本用法

本文详细介绍了Mybatis注解的使用,包括@Select、@Insert、@Update、@Delete等基本注解,以及@Results、@InsertProvider、@UpdateProvider、@DeleteProvider等高级用法,展示了如何进行字段映射、插入、更新和删除操作,同时讲解了Provider注解在处理复杂SQL时的应用。
摘要由CSDN通过智能技术生成

在Mybatis注解SQL中,最基本的就是@Select、@Insert、@Update、@Delete

  • @Select注解

RoleMapper接口:

package tk.mybatis.simple.mapper;

import org.apache.ibatis.annotations.Select;

import tk.mybatis.simple.model.SysRole;

public interface RoleMapper {
	//通过角色id查询角色
	@Select({"select id, role_name roleName, enabled, create_by createBy, create_time createTime from "
			+ "sys_role where id = #{id}"})
	SysRole selectById(Long id);
}

测试代码:

@Test
public void testSelectById(){
	SqlSession sqlSession = getSqlSession();
	try{
		//获取UserMapper接口
		RoleMapper userMapper = sqlSession.getMapper(RoleMapper.class);
		//调用selectById方法  查询id = 1的角色
		SysRole role = userMapper.selectById(1L);
		//user不为空
		Assert.assertNotNull(role);
		//roleName = 管理员
		Assert.assertEquals("管理员", role.getRoleName());
	}finally {
		sqlSession.close();
	}
}</
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 我可以回答这个问题。MyBatis 注解方式使用 where 子句可以在 SQL 语句中添加条件。可以使用 @Where 注解来指定 where 子句的条件,例如:@Where("name = 'Tom'")。也可以使用 @WhereProvider 注解来指定 where 子句的条件,例如:@WhereProvider(type = UserSqlProvider.class, method = "whereCondition")。在这个例子中,UserSqlProvider 是一个自定义的 SQL 语句提供者类,其中的 whereCondition 方法返回 where 子句的条件。 ### 回答2: Mybatis注解方式使用where可以通过@Select、@Update、@Delete注解的方法上使用@Param注解来传递参数,并且可以在SQL语句中使用动态的where条件。 在注解方式中,可以使用${}和#{}两种方式传递参数。其中,${}会直接将参数的值拼接到SQL语句中,而#{}则会使用预处理语句的方式传递参数,可以有效防止SQL注入。 下面是一个使用where条件的示例: @Select("SELECT * FROM user WHERE 1=1 " + "<if test=\"name != null and name != ''\"> AND name = #{name} </if> " + "<if test=\"age != null\"> AND age = #{age} </if> ") List<User> findUser(@Param("name") String name, @Param("age") Integer age); 在上述代码中,使用了where条件来动态拼接查询语句。where 1=1是为了保证该条件不为空,以便后续的条件可以使用AND连接。 在<if>标签中,使用了test属性来判断条件是否满足。当name不为空时,会拼接name = #{name}到SQL语句中;当age不为空时,会拼接age = #{age}到SQL语句中。 通过这种方式,可以根据传入的参数动态生成where条件,提高代码的灵活性和可重用性。 同时,需要注意的是,如果某个参数可能为空,需要进行非空判断,以避免查询出错或者无法返回正确的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值