springboot整合mybatisplus 登录案列
时间: 2023-11-21 16:57:24 浏览: 80
springboot整合mybatis
5星 · 资源好评率100%
以下是Spring Boot整合MyBatis Plus实现登录的案例:
1.首先,需要在pom.xml文件中添加MyBatis Plus和MySQL的依赖:
```xml
<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>
</dependency>
```
2.在application.properties文件中配置MySQL数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3.创建一个User实体类,用于映射数据库中的用户表:
```java
@Data
public class User {
private Long id;
private String username;
private String password;
}
```
4.创建一个UserMapper接口,用于操作用户表:
```java
public interface UserMapper extends BaseMapper<User> {
User selectByUsername(String username);
}
```
5.创建一个UserService类,用于处理用户相关的业务逻辑:
```java
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public User login(String username, String password) {
User user = baseMapper.selectByUsername(username);
if (user != null && user.getPassword().equals(password)) {
return user;
}
return null;
}
}
```
6.创建一个UserController类,用于处理用户登录请求:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(String username, String password) {
User user = userService.login(username, password);
if (user != null) {
return "登录成功";
} else {
return "用户名或密码错误";
}
}
}
```
7.最后,启动Spring Boot应用程序,并使用Postman等工具发送登录请求,即可实现登录功能。
阅读全文