mybatisplus根据Id查询用户信息代码怎么写
时间: 2023-08-02 19:10:58 浏览: 53
假设你的实体类为`User`,主键为`id`,使用Mybatis-Plus框架,根据id查询用户信息的代码如下:
```java
// 导入相关类
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
// 定义Mapper接口
public interface UserMapper extends BaseMapper<User> {
}
// 在Service中注入Mapper
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Long id) {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("id", id);
return userMapper.selectOne(wrapper);
}
}
```
其中,`QueryWrapper`是Mybatis-Plus提供的查询构造器,用于构建查询条件。这里我们使用`eq`方法,指定查询条件为`id = #{id}`,即根据主键id查询用户信息。`selectOne`方法表示查询一条记录,如果查询结果有多条记录,则会抛出异常。如果需要查询多条记录,则可以使用`selectList`方法。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)