springboot集合mybatis-plus,mysql 1.引入依赖和yml配置 2.创建数据库和数据表 3.创建user表对应的实体类(id,username,password) 4.整合mp,创建接口,继承mp的接口 5.用UserMapper查询username
时间: 2024-06-11 22:06:49 浏览: 81
springboot整合mybatis-plus实现多表分页查询
1. 引入依赖和yml配置
在pom.xml文件中引入如下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
```
在application.yml文件中配置数据源和mybatis-plus:
```
spring:
datasource:
url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
mapper-locations: classpath:mapper/*.xml
```
2. 创建数据库和数据表
在mysql中创建一个名为mytest的数据库,然后创建一个名为user的数据表:
```
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
3. 创建user表对应的实体类(id,username,password)
```
@Data
public class User {
private Long id;
private String username;
private String password;
}
```
4. 整合mp,创建接口,继承mp的接口
创建UserMapper接口,继承BaseMapper<User>接口:
```
public interface UserMapper extends BaseMapper<User> {
}
```
在mapper目录下创建UserMapper.xml文件,其中定义了具体的sql语句:
```
<?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="com.example.mapper.UserMapper">
<select id="selectByUsername" resultType="com.example.entity.User">
select * from user where username = #{username}
</select>
</mapper>
```
5. 用UserMapper查询username
在UserController中注入UserMapper,然后调用selectByUsername方法查询数据:
```
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/user/{username}")
public User getUserByUsername(@PathVariable String username){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("username", username);
return userMapper.selectOne(wrapper);
}
}
```
这里使用了QueryWrapper,可以方便地构造查询条件。最后访问http://localhost:8080/user/xxx,即可查询到对应的user信息。
阅读全文