用mybatis-plus-join写一个迷糊查询
时间: 2024-05-01 11:20:32 浏览: 75
mybatis 模糊查询的实现方法
5星 · 资源好评率100%
首先,需要在pom.xml中添加mybatis-plus和数据库驱动的依赖:
```xml
<dependencies>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
```
接着,创建实体类和mapper接口,以User和Order为例:
User实体类:
```java
@Data
public class User {
private Long id;
private String name;
private Integer age;
}
```
UserMapper接口:
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
```
Order实体类:
```java
@Data
public class Order {
private Long id;
private Long userId;
private String orderNo;
private Date createTime;
}
```
OrderMapper接口:
```java
@Mapper
public interface OrderMapper extends BaseMapper<Order> {
}
```
然后,在UserService中使用mybatis-plus-join实现迷糊查询:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private OrderMapper orderMapper;
public List<User> findUsersByNameLike(String name) {
QueryWrapper<User> userWrapper = new QueryWrapper<>();
userWrapper.like("name", name);
return userMapper.selectList(userWrapper);
}
public List<User> findUsersByOrderCreateTimeBetween(Date start, Date end) {
QueryWrapper<User> userWrapper = new QueryWrapper<>();
userWrapper.inSql("id", "select user_id from `order` where create_time between #{start} and #{end}");
return userMapper.selectList(userWrapper);
}
public List<User> findUsersByOrderNoLike(String orderNo) {
QueryWrapper<User> userWrapper = new QueryWrapper<>();
userWrapper.inSql("id", "select user_id from `order` where order_no like concat('%', #{orderNo}, '%')");
return userMapper.selectList(userWrapper);
}
public List<User> findUsersByOrderNoLikeAndAgeBetween(String orderNo, Integer startAge, Integer endAge) {
QueryWrapper<User> userWrapper = new QueryWrapper<>();
userWrapper.inSql("id", "select user_id from `order` where order_no like concat('%', #{orderNo}, '%')")
.between("age", startAge, endAge);
return userMapper.selectList(userWrapper);
}
}
```
其中,findUsersByNameLike方法实现了根据用户姓名模糊查询的功能;findUsersByOrderCreateTimeBetween方法实现了查询在某个时间范围内下单的用户列表;findUsersByOrderNoLike方法实现了根据订单号模糊查询的功能;findUsersByOrderNoLikeAndAgeBetween方法实现了根据订单号模糊查询,并且年龄在某个范围内的用户列表。
阅读全文