MyBatis 动态 SQL

本文介绍了如何在MyBatis中使用动态SQL进行查询。通过不同的参数组合,如id、username、password和age,动态拼接SQL查询User。在UserRepository中定义了相应的方法,并详细讲解了动态SQL的实现,包括if、where、choose、when、trim和set标签的应用。
摘要由CSDN通过智能技术生成

MyBatis 动态 SQL

public class User{
   
 private Integer id;
 private String username;
 private String password;
 private Integer age; }

通过 id 和 username 查询 User。
通过 username 和 password 查询 User。
通过 password 和 age 查询 User。

在 UserRepository 中定义上述 3 个方法

public User findByUser1(User user);
public User findByUser2(User user);
public User findByUser3(User user);

UserRepository.xml

<select id="findByUser1" parameterType="User" resultType="User">
 select * from t_user where id = #{id} and username = #{username}
</select> <select id="findByUser2" parameterType="User" resultType="User">
 select * from t_user where username = #{username} and password = #{password}
</select> <select id="findByUser3" parameterType="User" resultType="User">
 select * from t_user where password = #{password} and age = #{age}
</select>

MyBatis 动态 SQL,SQL 不是固定的,可以根据不同的参数信息来动态拼接不同的 SQL,以适应不同的需求。
1、创建实体类

public class User{
   
 private Integer id;
 private String username;
 private String password;
 private Integer age; }

2、Mapper.java

package com.southwind.repository;
import com.southwind.entity.User;
public interface UserRepository {
   
 public User findByUser(User user);
}

3、Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

走不尽的心路

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

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

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

打赏作者

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

抵扣说明:

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

余额充值